From 435b2173d67dd286fb76dc9569b79008b14c607d Mon Sep 17 00:00:00 2001 From: Seb James Date: Sun, 29 Nov 2026 11:31:57 +0000 Subject: [PATCH 1/5] Avoids export import in VisualOwnable --- mplot/VisualOwnable.cppm | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/mplot/VisualOwnable.cppm b/mplot/VisualOwnable.cppm index b49e7c8f..4d029ad2 100644 --- a/mplot/VisualOwnable.cppm +++ b/mplot/VisualOwnable.cppm @@ -39,24 +39,24 @@ module; export module mplot.visualownable; -export import mplot.version; -export import mplot.visualmodel; -export import mplot.win_t; -export import mplot.visualcommon; +import mplot.version; +import mplot.visualmodel; +import mplot.win_t; +import mplot.visualcommon; import mplot.visualresources; -export import mplot.visualtextmodel; -export import mplot.textgeometry; -export import mplot.textfeatures; +import mplot.visualtextmodel; +import mplot.textgeometry; +import mplot.textfeatures; import mplot.coordarrows; -export import mplot.gl.version; +import mplot.gl.version; import mplot.gl.util; import mplot.tools; import mplot.loadpng; // Use Lode Vandevenne's PNG encoder -export import mplot.keys; +import mplot.keys; import sm.mathconst; -export import sm.vec; -export import sm.flags; +import sm.vec; +import sm.flags; import sm.quaternion; import sm.mat; From 96b582ce3dcf0662b8cba44881e603fa2e08ba8a Mon Sep 17 00:00:00 2001 From: Seb James Date: Sun, 29 Nov 2026 13:09:13 +0000 Subject: [PATCH 2/5] NavMesh does not need to be a partition, simpler if it ain't --- cmake/module_definitions.cmake | 6 +- modules/VisualModel.cppm | 24 + modules/VisualOwnable.cppm | 33 + modules/VisualResources.cppm | 18 + mplot/CMakeLists.txt | 6 +- mplot/NavMesh.cppm | 2 +- mplot/VisualModel.cppm | 2 +- mplot/VisualModel.hpp | 3949 ++++++++++++++++++++++++++++++++ mplot/VisualOwnable.hpp | 2495 ++++++++++++++++++++ mplot/VisualResources.hpp | 375 +++ 10 files changed, 6902 insertions(+), 8 deletions(-) create mode 100644 modules/VisualModel.cppm create mode 100644 modules/VisualOwnable.cppm create mode 100644 modules/VisualResources.cppm create mode 100644 mplot/VisualModel.hpp create mode 100644 mplot/VisualOwnable.hpp create mode 100644 mplot/VisualResources.hpp diff --git a/cmake/module_definitions.cmake b/cmake/module_definitions.cmake index 6efa1270..390e38cf 100644 --- a/cmake/module_definitions.cmake +++ b/cmake/module_definitions.cmake @@ -76,17 +76,17 @@ macro(setup_module_variables_for_mathplot base_directory maths_directory) ${base_directory}/mplot/colour.cppm ${base_directory}/mplot/win_t.cppm ${base_directory}/mplot/CoordArrows.cppm - ${base_directory}/mplot/VisualOwnable.cppm + ${base_directory}/modules/VisualOwnable.cppm ${base_directory}/mplot/Visual.cppm ${base_directory}/mplot/VisualGlfw.cppm ${base_directory}/mplot/VisualFace.cppm ${base_directory}/mplot/TextFeatures.cppm ${base_directory}/mplot/TextGeometry.cppm - ${base_directory}/mplot/VisualResources.cppm + ${base_directory}/modules/VisualResources.cppm ${base_directory}/mplot/VisualCommon.cppm ${base_directory}/mplot/VisualFont.cppm ${base_directory}/mplot/VisualTextModel.cppm - ${base_directory}/mplot/VisualModel.cppm + ${base_directory}/modules/VisualModel.cppm ${base_directory}/mplot/NavMesh.cppm ${base_directory}/mplot/ColourMap.cppm ${base_directory}/mplot/colourmaps_cet.cppm diff --git a/modules/VisualModel.cppm b/modules/VisualModel.cppm new file mode 100644 index 00000000..7316f683 --- /dev/null +++ b/modules/VisualModel.cppm @@ -0,0 +1,24 @@ +/*! + * \file + * + * cppm wrapper + * + * \author Seb James + * \date Nov 2026 + */ +module; + +#include + +export module mplot.visualmodel; + +export import mplot.gl.version; +export import mplot.textfeatures; +export import mplot.textgeometry; +export import mplot.colour; +export import mplot.visualresources; + +export namespace mplot +{ + using mplot::VisualModel; +} diff --git a/modules/VisualOwnable.cppm b/modules/VisualOwnable.cppm new file mode 100644 index 00000000..754e9bb4 --- /dev/null +++ b/modules/VisualOwnable.cppm @@ -0,0 +1,33 @@ +/*! + * \file + * + * Awesome graphics code for high performance graphing and visualisation. + * + * This is intermediate class that sets up (multicontext aware) GL, leaving choice of window system + * (GLFW3/Qt/wx/etc) to a derived class such as mplot::Visual or mplot::qt::viswidget. + * + * This class is 'ownable', and can be used in other window drawing system such as Qt and wx, as + * well as within mplot::Visual, which marries it with the GLFW3 windowing system. + * + * Created by Seb James on 2026/11/29, as a wrapper around a header. + * + * \author Seb James + * \date March 2025 + */ +module; + +#include + +export module mplot.visualownable; + +export import mplot.version; + +export namespace mplot +{ + using mplot::visual_state; + using mplot::visual_options; + using mplot::perspective_type; + using mplot::direction_event; + using mplot::direction_data; + using mplot::VisualOwnable; +} // namespace mplot diff --git a/modules/VisualResources.cppm b/modules/VisualResources.cppm new file mode 100644 index 00000000..39f8342b --- /dev/null +++ b/modules/VisualResources.cppm @@ -0,0 +1,18 @@ +/*! + * \file + * + * cppm wrapper for VisualResources.hpp + * + * \author Seb James + * \date November 2026 + */ +module; + +#include + +export module mplot.visualresources; + +export namespace mplot +{ + using mplot::VisualResources; +} diff --git a/mplot/CMakeLists.txt b/mplot/CMakeLists.txt index 8304b1f2..9c78e992 100644 --- a/mplot/CMakeLists.txt +++ b/mplot/CMakeLists.txt @@ -76,9 +76,9 @@ install( VisualFace.cppm VisualFont.cppm VisualGlfw.cppm - VisualModel.cppm - VisualOwnable.cppm - VisualResources.cppm + VisualModel.hpp + VisualOwnable.hpp + VisualResources.hpp VisualTextModel.cppm VoronoiVisual.cppm win_t.cppm diff --git a/mplot/NavMesh.cppm b/mplot/NavMesh.cppm index 5eafb1cb..df28f2f2 100644 --- a/mplot/NavMesh.cppm +++ b/mplot/NavMesh.cppm @@ -23,7 +23,7 @@ module; #include #include -export module mplot.visualmodel:navmesh; +export module mplot.navmesh; import sm.vec; import sm.vvec; diff --git a/mplot/VisualModel.cppm b/mplot/VisualModel.cppm index 7a514012..4c524a30 100644 --- a/mplot/VisualModel.cppm +++ b/mplot/VisualModel.cppm @@ -57,7 +57,7 @@ export import mplot.colour; import mplot.gl.util; import mplot.tools; -export import :navmesh; +export import mplot.navmesh; export namespace mplot { diff --git a/mplot/VisualModel.hpp b/mplot/VisualModel.hpp new file mode 100644 index 00000000..9d1e8119 --- /dev/null +++ b/mplot/VisualModel.hpp @@ -0,0 +1,3949 @@ +/*! + * \file + * + * Declares a VisualModel base class to hold the vertices that make up some individual model object + * that can be part of an OpenGL scene. + * + * GL function calls are added in VisualModel.h + * + * \author Seb James + * \date March 2025 + */ +#pragma once + +#if defined __gl3_h_ || defined __gl_h_ +// GL headers have been externally included +#else +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +import sm.mathconst; +import sm.geometry; +import sm.geometry_polyhedra; +import sm.quaternion; +import sm.mat; +import sm.vec; +import sm.vvec; +import sm.interval; +import sm.algo; +import sm.flags; +import sm.base64; + +// Need to import common here +import mplot.gl.version; +import mplot.visualcommon; +//import mplot.visualresources; +import mplot.visualtextmodel; +import mplot.colour; +import mplot.gl.util; +import mplot.tools; + +import mplot.navmesh; + +namespace mplot +{ + union float_bytes // for gltf output + { + float f; + std::uint8_t bytes[sizeof(float)]; + }; + + /*! + * An OpenGL model class + * + * This class is the 'OpenGL model' class. It has the common code to create the vertices for + * some individual OpenGL model which is to be rendered in a 3-D scene. + * + * Some OpenGL models are derived directly from VisualModel; see for example mplot::CoordArrows. + * + * Other models in mathplot are derived via mplot::VisualDataModel, which adds a common + * mechanism for managing the data which is to be visualised by the final 'Visual' object (such + * as mplot::HexGridVisual or mplot::ScatterVisual) + * + * This class contains some common 'object primitives' code, such as computeSphere and + * computeCone, which compute the vertices that will make up sphere and cone, respectively. + */ + template + struct VisualModel + { + VisualModel() {} + VisualModel (const sm::vec _offset) { this->viewmatrix.translate (_offset); } + + //! destroy gl buffers in the deconstructor + virtual ~VisualModel() // clang gives -Wdelete-non-abstract-non-virtual-dtor without virtual + { + // Explicitly clear owned VisualTextModels + this->texts.clear(); + if (this->vbos != nullptr) { + GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + if (glfn) { + glfn->DeleteBuffers (this->numVBO, this->vbos.get()); + glfn->DeleteVertexArrays (1, &this->vao); + } + } + } + + //! Common code to call after the vertices have been set up. GL has to have been initialised. + void postVertexInit() + { + if (this->parentVis == std::numeric_limits::max()) { + throw std::runtime_error ("parentVis is unset"); + } + GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + + // Do gl memory allocation of vertex array once only + if (this->vbos == nullptr) { + // Create vertex array object + glfn->GenVertexArrays (1, &this->vao); // Safe for OpenGL 4.4- + } + glfn->BindVertexArray (this->vao); + + // Create the vertex buffer objects (once only) + if (this->vbos == nullptr) { + this->vbos = std::make_unique(this->numVBO); + glfn->GenBuffers (this->numVBO, this->vbos.get()); // OpenGL 4.4- safe + } + + // Set up the indices buffer - bind and buffer the data in this->indices + glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]); + + std::size_t sz = this->indices.size() * sizeof(std::uint32_t); + glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW); + + // Binds data from the "C++ world" to the OpenGL shader world for + // "position", "normalin" and "color" + // (bind, buffer and set vertex array object attribute) + this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc, 3); + this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc, 3); + this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc, this->ncol); + + // Unbind only the vertex array (not the buffers, that causes GL_INVALID_ENUM errors) + glfn->BindVertexArray(0); // carefully unbind and rebind + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + + if (this->flags.test (vm_bools::instanced)) { + // Here, we cause the SSBOs to be intialized if they haven't already, and we reserve + // some space in the SSBOs for *this model* + this->instance_start = mplot::VisualResources::i().init_instance_ssbo (this->parentVis, this->max_instances); + if (this->instance_start == std::numeric_limits::max()) { + throw std::runtime_error ("Failed to reserve space in SSBO"); + } + } + + /* + * Now do the same for the bounding box + */ + if (this->flags.test (vm_bools::compute_bb)) { + + if (this->vbos_bb == nullptr) { glfn->GenVertexArrays (1, &this->vao_bb); } + glfn->BindVertexArray (this->vao_bb); + + // Create the vertex buffer objects (once only) + if (this->vbos_bb == nullptr) { + this->vbos_bb = std::make_unique(this->numVBO); + glfn->GenBuffers (this->numVBO, this->vbos_bb.get()); + } + + // Set up the indices buffer - bind and buffer the data in this->indices + glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos_bb[this->idxVBO]); + + std::size_t sz = this->indices_bb.size() * sizeof(std::uint32_t); + glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices_bb.data(), GL_STATIC_DRAW); + + // Binds data from the "C++ world" to the OpenGL shader world for + // "position", "normalin" and "color" + // (bind, buffer and set vertex array object attribute) + this->setupVBO (this->vbos_bb[this->posnVBO], this->vpos_bb, visgl::posnLoc, 3); + this->setupVBO (this->vbos_bb[this->normVBO], this->vnorm_bb, visgl::normLoc, 3); + this->setupVBO (this->vbos_bb[this->colVBO], this->vcol_bb, visgl::colLoc, this->ncol); + + // Unbind only the vertex array (not the buffers, that causes GL_INVALID_ENUM errors) + glfn->BindVertexArray(0); // carefully unbind and rebind + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + } + + this->flags.set (vm_bools::postVertexInitRequired, false); + } + + //! Initialize vertex buffer objects and vertex array object. Empty for 'text only' VisualModels. + virtual void initializeVertices() {}; + /*! + * Helper to make a VisualTextModel and set its parent so it is ready for use. + * + * You could write it out explicitly as: + * + * std::unique_ptr> vtm1 = this->makeVisualTextModel (tfca); + * + * Or use auto to help: + * + * auto vtm1 = this->makeVisualTextModel (tfca); + * + * See GraphVisual.h for examples. + */ + std::unique_ptr> makeVisualTextModel(const mplot::TextFeatures& tf) + { + auto tmup = std::make_unique> (tf); + tmup->set_parent (this->parentVis); + return tmup; + } + + /*! + * Add a text label to the model at location (within the model coordinates) + * toffset. Return the text geometry of the added label so caller can place + * associated text correctly. Control font size, resolution, colour and font + * face with TextFeatures tf. + */ + mplot::TextGeometry addLabel (const std::string& _text, + const sm::vec& _toffset, + const mplot::TextFeatures& tf = mplot::TextFeatures()) + { + if (mplot::VisualResources::i().get_tprog (this->parentVis) == 0) { + throw std::runtime_error ("No text shader prog. Did your VisualModel-derived class set it up?"); + } + + mplot::VisualResources::i().setContext (this->parentVis); // For VisualTextModel + + auto tmup = this->makeVisualTextModel (tf); + + if (tf.centre_horz == true) { + mplot::TextGeometry tg = tmup->getTextGeometry(_text); + sm::vec centred_locn = _toffset; + centred_locn[0] -= tg.half_width(); + tmup->setupText (_text, centred_locn + this->viewmatrix.translation(), tf.colour); + } else { + tmup->setupText (_text, _toffset + this->viewmatrix.translation(), tf.colour); + } + + this->texts.push_back (std::move(tmup)); + + // As this is a setup function, release the context + mplot::VisualResources::i().releaseContext(); + + return this->texts.back()->getTextGeometry(); + } + + /*! + * Add a text label, with given offset _toffset and the specified tf. The + * reference to a pointer, tm, allows client code to change the text of the + * VisualTextModel as necessary, after the label has been added. + */ + mplot::TextGeometry addLabel (const std::string& _text, + const sm::vec& _toffset, + mplot::VisualTextModel*& tm, + const mplot::TextFeatures& tf = mplot::TextFeatures()) + { + if (mplot::VisualResources::i().get_tprog (this->parentVis) == 0) { + throw std::runtime_error ("No text shader prog. Did your VisualModel-derived class set it up?"); + } + + mplot::VisualResources::i().setContext (this->parentVis); // For VisualTextModel + + auto tmup = this->makeVisualTextModel (tf); + + if (tf.centre_horz == true) { + mplot::TextGeometry tg = tmup->getTextGeometry(_text); + sm::vec centred_locn = _toffset; + centred_locn[0] -= tg.half_width(); + tmup->setupText (_text, centred_locn + this->viewmatrix.translation(), tf.colour); + } else { + tmup->setupText (_text, _toffset + this->viewmatrix.translation(), tf.colour); + } + + this->texts.push_back (std::move(tmup)); + tm = this->texts.back().get(); + + // As this is a setup function, release the context + mplot::VisualResources::i().releaseContext(); + + return this->texts.back()->getTextGeometry(); + } + + void setSceneMatrixTexts (const sm::mat& sv) + { + auto ti = this->texts.begin(); + while (ti != this->texts.end()) { (*ti)->setSceneMatrix (sv); ti++; } + } + + void setSceneTranslationTexts (const sm::vec& v0) + { + auto ti = this->texts.begin(); + while (ti != this->texts.end()) { (*ti)->setSceneTranslation (v0); ti++; } + } + + void setViewRotationTexts (const sm::quaternion& r) + { + // When rotating a model that contains texts, we need to rotate the scene + // for the texts and also inverse-rotate the view of the texts. + auto ti = this->texts.begin(); + while (ti != this->texts.end()) { + // Rotate the scene. Note this won't work if the VisualModel has a + // translation away from the origin. + (*ti)->setSceneRotation (r); // Need this to rotate about _offset. BUT the + // translation is already there in the text, + // but in the MODEL view. + + // Rotate the view of the text an opposite amount, to keep it facing forwards + (*ti)->setViewRotation (r.invert()); + ti++; + } + } + + void addViewRotationTexts (const sm::quaternion& r) + { + auto ti = this->texts.begin(); + while (ti != this->texts.end()) { (*ti)->addViewRotation (r); ti++; } + } + + //! Process vertices and find the bounding box + void update_bb() + { + if (this->flags.test (vm_bools::compute_bb) == false) { return; } + + if (this->vertexPositions.size() % 3 != 0) { + throw std::runtime_error ("VisualModelBase: vertexPositions size is not divisible by 3"); + } + this->bb.search_init(); + for (std::size_t i = 0; i < this->vertexPositions.size(); i += 3) { + this->bb.update (sm::vec{ vertexPositions[i], vertexPositions[i+1], vertexPositions[i+2] }); + } + // Construct the half-extent axis vectors, too. + const sm::vec bb_ext = this->bb.span() / 2.0f; + this->bb_x = { bb_ext[0], 0, 0 }; // i.e. bb_ext[0] * sm::vec<>::ux(); + this->bb_y = { 0, bb_ext[1], 0 }; + this->bb_z = { 0, 0, bb_ext[2] }; + + // After finding the bounding box, make up the vertices to display it: + this->computeBoundingBox(); + } + + /*! + * Re-initialize the buffers. Client code might have appended to + * vertexPositions/Colors/Normals and indices before calling this method. + */ + void reinit_buffers() + { + GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + + mplot::VisualResources::i().setContext (this->parentVis); + if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); } + + // Now re-set up the VBOs + glfn->BindVertexArray (this->vao); // carefully unbind and rebind + glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]); // carefully unbind and rebind + + std::size_t sz = this->indices.size() * sizeof(std::uint32_t); + glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW); + this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc, 3); + this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc, 3); + this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc, this->ncol); + + glfn->BindVertexArray(0); // carefully unbind and rebind + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); // carefully unbind and rebind + + // Optional bounding box + if (this->flags.test (vm_bools::compute_bb)) { + glfn->BindVertexArray (this->vao_bb); + glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos_bb[this->idxVBO]); + + std::size_t sz = this->indices_bb.size() * sizeof(std::uint32_t); + glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices_bb.data(), GL_STATIC_DRAW); + this->setupVBO (this->vbos_bb[this->posnVBO], this->vpos_bb, visgl::posnLoc, 3); + this->setupVBO (this->vbos_bb[this->normVBO], this->vnorm_bb, visgl::normLoc, 3); + this->setupVBO (this->vbos_bb[this->colVBO], this->vcol_bb, visgl::colLoc, this->ncol); + + glfn->BindVertexArray(0); + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + } + } + + //! reinit ONLY vertexColors buffer + void reinit_colour_buffer() + { + mplot::VisualResources::i().setContext (this->parentVis); + if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); } + GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + // Now re-set up the VBOs + glfn->BindVertexArray (this->vao); // carefully unbind and rebind + this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc, this->ncol); + glfn->BindVertexArray(0); // carefully unbind and rebind + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + } + + void clearTexts() { this->texts.clear(); } + + //! Clear out the model, *including text models* + void clear() + { + this->vertexPositions.clear(); + this->vertexNormals.clear(); + this->vertexColors.clear(); + this->indices.clear(); + this->clearTexts(); + this->idx = 0u; + // Clear bounding box + this->vpos_bb.clear(); + this->vnorm_bb.clear(); + this->vcol_bb.clear(); + this->indices_bb.clear(); + this->idx_bb = 0u; + + this->reinit_buffers(); + } + + //! Re-create the model - called after updating data + void reinit() + { + mplot::VisualResources::i().setContext (this->parentVis); + // Fixme: Better not to clear, then repeatedly pushback here: + this->vertexPositions.clear(); + this->vertexNormals.clear(); + this->vertexColors.clear(); + this->indices.clear(); + + // Clear any bounding box too + this->vpos_bb.clear(); + this->vnorm_bb.clear(); + this->vcol_bb.clear(); + this->indices_bb.clear(); + this->idx_bb = 0u; + + // NB: Do NOT call clearTexts() here! We're only updating the model itself. + this->idx = 0u; + this->initializeVertices(); + // Add additional meshgroups + for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); } + this->update_bb(); + this->reinit_buffers(); + } + + /*! + * For some models it's important to clear the texts when reinitialising. This is NOT the + * same as VisualModel::clear() followed by initializeVertices(). For the same effect, you + * can call clearTexts() then reinit(). + */ + void reinit_with_clearTexts() + { + mplot::VisualResources::i().setContext (this->parentVis); + this->vertexPositions.clear(); + this->vertexNormals.clear(); + this->vertexColors.clear(); + this->indices.clear(); + + this->clearTexts(); + this->idx = 0u; + + // Clear any bounding box too + this->vpos_bb.clear(); + this->vnorm_bb.clear(); + this->vcol_bb.clear(); + this->indices_bb.clear(); + this->idx_bb = 0u; + + this->initializeVertices(); + for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); } + this->update_bb(); + this->reinit_buffers(); + } + + void reserve_vertices (std::size_t n_vertices) + { + this->vertexPositions.reserve (3u * n_vertices); + this->vertexNormals.reserve (3u * n_vertices); + this->vertexColors.reserve (this->ncol * n_vertices); + this->indices.reserve (6u * n_vertices); + } + + // Make a hash of vertexPositions, etc as an identifier for this model. The hash identifies + // the model's mesh geometry for NavMesh and so the vertexColors are not important. + std::size_t hash() const + { + std::size_t h = 17; + for (std::size_t i = 0u; i < this->vertexPositions.size(); ++i) { + h = (h << 5) - 1 + std::hash{}(this->vertexPositions[i]); + } + for (std::size_t i = 0u; i < this->vertexNormals.size(); ++i) { + h = (h << 5) - 1 + std::hash{}(this->vertexNormals[i]); + } + for (std::size_t i = 0u; i < this->indices.size(); ++i) { + h = (h << 5) - 1 + std::hash{}(this->indices[i]); + } + return h; + } + + // Get a single position from vertexPositions, using the index into the vector + // interpretation of vertexPositions + sm::vec get_position (const std::uint32_t vec_idx) const + { + auto vp = reinterpret_cast>*>(&this->vertexPositions); + return (*vp)[vec_idx]; + } + + // Get a single normal from vertexNormals, using the index into the vector + // interpretation of vertexNormals + sm::vec get_normal (const std::uint32_t vec_idx) const + { + auto vn = reinterpret_cast>*>(&this->vertexNormals); + return (*vn)[vec_idx]; + } + + // Get the area of the triangle whose start index is vec_idx + float get_area (const std::uint32_t vec_idx0, const std::uint32_t vec_idx1, const std::uint32_t vec_idx2) const + { + auto vp = reinterpret_cast>*>(&this->vertexPositions); + auto t0 = (*vp)[vec_idx0]; + auto t1 = (*vp)[vec_idx1]; + auto t2 = (*vp)[vec_idx2]; + return sm::geometry::tri_area (t0, t1, t2); + } + + /** + * Neighbour vertex mesh code. + */ + + // Our navigation mesh data struct + std::unique_ptr navmesh; + + void build_navmesh() + { + constexpr bool debug_mn = false; + if constexpr (debug_mn) { std::cout << __func__ << " called" << std::endl; } + + if (!this->navmesh) { return; } + + // Copy the bounding box + navmesh->bb = this->bb; + + // Treat vertexPositions as a vector of vec: + auto vp = reinterpret_cast>*>(&this->vertexPositions); + + std::uint32_t vps = vp->size(); + std::unordered_map, std::set, sm::vec::hash> equiv_v; + std::uint32_t i = 0; + for (auto p : *vp) { equiv_v[p].insert (i++); } + std::map> equiv; + for (auto e : equiv_v) { equiv[*e.second.begin()] = e.second; } + if constexpr (debug_mn) { + for (auto e : equiv) { + std::cout << "build_navmesh: equiv[" << e.first << "] = "; + for (auto idx : e.second) { std::cout << idx << ","; } + std::cout << std::endl; + } + std::cout << "build_navmesh: Populated equiv which has " << equiv.size() << " vvecs" << std::endl; + } + + // Make inverse of equiv to translate from original (indices, vertexPositions) index to + // new topographic mesh index + sm::vvec navmesh_idx (vps, 0); + std::uint32_t vcount = 0; + i = 0; + for (auto eqs : equiv) { + vcount += eqs.second.size(); + for (auto ev : eqs.second) { + if constexpr (debug_mn) { + std::cout << "build_navmesh: set navmesh_idx[" << ev << "] = " << i << std::endl; + } + navmesh_idx[ev] = i; + } + ++i; + } + if constexpr (debug_mn) { std::cout << "build_navmesh: Created equiv inverse" << std::endl; } + + if (vcount != vps) { + std::cout << "build_navmesh: WARNING: Vertex count from equiv is " << vcount + << " which should (but does not) equal " << vps << std::endl; + } + + // Can now populate vertex, a vector of coordinates, if required, or simply access (*vp) + // as needed using equiv.first + navmesh->vertex.resize (equiv.size(), mesh::vertex{}); + i = 0; + for (auto eq : equiv) { + navmesh->vertex[i++] = { (*vp)[eq.first], std::numeric_limits::max() }; + } + + // We're turing a triangle mesh into a navmesh. Don't know what to do if there are stray vertices. + if (this->indices.size() % 3u != 0u) { + throw std::runtime_error ("Uh oh, indices size not divisible by 3!!!! Call the cops!"); + } + + // Lastly, generate edges. For which we require use of indices, which is expressed in + // terms of the old indices. That lookup is navmesh_idx. + for (std::uint32_t i = 0; i < this->indices.size(); i += 3) { + + // Add three halfedges for the triangle + const std::uint32_t hesz = navmesh->halfedge.size(); + const std::uint32_t he0 = hesz; + const std::uint32_t he1 = hesz + 1; + const std::uint32_t he2 = hesz + 2; + + if constexpr (debug_mn) { + std::cout << "setting halfedge["<< he0 << "] to { {" + << navmesh_idx[indices[i]] << ", " << navmesh_idx[indices[i + 1]] + << "}, nullptr, " << he1 << ", " << he2 << " }" << std::endl; + + std::cout << "setting halfedge[" << he1 << "] to { {" + << navmesh_idx[indices[i + 1]] << ", " << navmesh_idx[indices[i + 2]] + << "}, nullptr, " << he2 << ", " << he0 << " }" << std::endl; + + std::cout << "setting halfedge[" << he2 << "] to { {" + << navmesh_idx[indices[i + 2]] << ", " << navmesh_idx[indices[i]] + << "}, nullptr, " << he0 << ", " << he1 << " }" << std::endl; + } + + navmesh->halfedge.resize (hesz + 3, {}); + + // Now, could also try to identify LINES + navmesh->halfedge[he0] = { {navmesh_idx[indices[i ]], navmesh_idx[indices[i + 1]]}, std::numeric_limits::max(), he1, he2, 0u }; + navmesh->halfedge[he1] = { {navmesh_idx[indices[i + 1]], navmesh_idx[indices[i + 2]]}, std::numeric_limits::max(), he2, he0, 0u }; + navmesh->halfedge[he2] = { {navmesh_idx[indices[i + 2]], navmesh_idx[indices[i ]]}, std::numeric_limits::max(), he0, he1, 0u }; + + if constexpr (debug_mn) { + std::cout << "halfedge["<< hesz << "] contains: vi:" + << navmesh->halfedge[hesz].vi + << ", twin:" << navmesh->halfedge[hesz].twin + << ", next:" << navmesh->halfedge[hesz].next + << ", prev:" << navmesh->halfedge[hesz].prev << std::endl; + } + // A face contains just the first half edge index + mesh::face<> t = { he0 }; + + // The normal vector for this triangle could be obtained from the mesh normals, but + // we can't trust them (though they're easy to get, as we're dealing with indices + // already). However, use this to ensure that our triangle indices order is in + // agreement with mesh normal as far as direction goes. + sm::vec tn = this->get_normal (indices[i]) + this->get_normal (indices[i + 1]) + this->get_normal (indices[i + 2]) ; + tn.renormalize(); + + // Compute trinorm as well and compare with the one from the mesh - perhaps it's + // different? We really want the right normal. + const sm::vec& tv0 = navmesh->vertex[navmesh_idx[indices[i]]].p; + const sm::vec& tv1 = navmesh->vertex[navmesh_idx[indices[i + 1]]].p; + const sm::vec& tv2 = navmesh->vertex[navmesh_idx[indices[i + 2]]].p; + sm::vec nx = (tv1 - tv0); + sm::vec ny = (tv2 - tv0); + sm::vec n = nx.cross (ny); + n.renormalize(); + + // Check rotational sense of triangles + if (n.dot (tn) < 0.0f) { + std::cout << "Swap order of triangle with he " << he0 << std::endl; + // Swap first and last half edge + navmesh->halfedge[he0].vi.rotate(); + navmesh->halfedge[he1].vi.rotate(); + navmesh->halfedge[he2].vi.rotate(); + } + navmesh->triangles.push_back (t); + } + if constexpr (debug_mn) { + std::cout << "build_navmesh: Created triangles (" << navmesh->halfedge.size() << " halfedges)" << std::endl; + } + + navmesh->compute_neighbour_relations(); // finds the halfedge twins + } + + /*! + * Post-process vertices to generate a neighbour relationship mesh suitable for navigation. + * + * \param navmesh_dir The directory into which to store/read the navmesh data file. + */ + void make_navmesh (std::string navmesh_dir = "") + { + if (this->navmesh) { return; } // already made it + + if (this->flags.test (vm_bools::compute_bb) == false) { + throw std::runtime_error ("make_navmesh requires compute_bb flag to be true"); + } + this->update_bb(); + + // Create a new navmesh + this->navmesh = std::make_unique(); + + // Have we got a pre-computed navmesh file for the halfedge twin relationships? + std::uint64_t h = this->hash(); + if (navmesh_dir.empty()) { + navmesh_dir = mplot::tools::getTmpPath(); + } else { + if (navmesh_dir.back() != '/') { navmesh_dir += "/"; } + } + std::string filename = navmesh_dir + std::string("navmesh_") + std::to_string (h); + std::string filename_pre_boundary = filename + ".pre"; + + constexpr bool just_mark = true; + if (mplot::tools::fileExists (filename)) { + this->navmesh->load (filename); + std::cout << "Full test...\n"; + this->navmesh->test(); + + } else if (mplot::tools::fileExists (filename_pre_boundary)) { + std::cout << "Pre-boundary navmesh\n"; + this->navmesh->load (filename_pre_boundary); + this->navmesh->add_boundary_halfedges(); + this->navmesh->test (just_mark); + this->navmesh->save (filename); + } else { + std::cout << "Building NavMesh to save into file " << filename << std::endl; + this->build_navmesh(); + this->navmesh->save (filename_pre_boundary); + this->navmesh->add_boundary_halfedges(); + this->navmesh->test (just_mark); + this->navmesh->save (filename); + } + } + + /** + * End neighbour vertex mesh code + */ + + /*! + * A function to call initialiseVertices and postVertexInit after any necessary attributes + * have been set (see, for example, setting the colour maps up in VisualDataModel). + */ + void finalize() + { + mplot::VisualResources::i().setContext (this->parentVis); // need context? yes for text. + this->initializeVertices(); + for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); } + this->update_bb(); + this->flags.set (vm_bools::postVertexInitRequired, true); + // Release context after creating and finalizing this VisualModel. On Visual::render(), + // context will be re-acquired. + mplot::VisualResources::i().releaseContext(); + } + + static constexpr bool debug_render = false; + //! Render the VisualModel. Note that it is assumed that the OpenGL context has been + //! obtained by the parent Visual::render call. + virtual void render() // not final + { + if (this->hidden() == true) { return; } + + // Execute post-vertex init at render, as GL should be available. + if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); } + + std::int32_t prev_shader = 0; + + GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + glfn->GetIntegerv (GL_CURRENT_PROGRAM, &prev_shader); + // Ensure the correct program is in play for this VisualModel + std::uint32_t gprog = mplot::VisualResources::i().get_gprog (this->parentVis); + glfn->UseProgram (gprog); + + if (!this->indices.empty()) { + + // glPolygonMode is OpenGL only and not supported on GL ES + if constexpr (mplot::gl::version::gles (glver) == false) { + // Enable/disable wireframe mode per-model on each render call + if (this->flags.test (vm_bools::wireframe)) { + glfn->PolygonMode (GL_FRONT_AND_BACK, GL_LINE); + } else { + glfn->PolygonMode (GL_FRONT_AND_BACK, GL_FILL); + } + } + + // It is only necessary to bind the vertex array object before rendering + // (not the vertex buffer objects) + glfn->BindVertexArray (this->vao); + + // Pass this->float to GLSL so the model can have an alpha value. + std::int32_t loc_a = glfn->GetUniformLocation (gprog, static_cast("alpha")); + if (loc_a != -1) { glfn->Uniform1f (loc_a, this->alpha); } + + std::int32_t loc_gr = glfn->GetUniformLocation (gprog, static_cast("greyscale")); + if (loc_gr != -1) { glfn->Uniform1i (loc_gr, (this->flags.test (vm_bools::greyscale) ? 1 : 0)); } + + std::int32_t loc_gam = glfn->GetUniformLocation (gprog, static_cast("gamma")); + if (loc_gam != -1) { glfn->Uniform1f (loc_gam, this->gamma); } + + // The scene-view matrix + std::int32_t loc_v = glfn->GetUniformLocation (gprog, static_cast("v_matrix")); + if (loc_v != -1) { glfn->UniformMatrix4fv (loc_v, 1, GL_FALSE, this->scenematrix.arr.data()); } + + // the model-view matrix + std::int32_t loc_m = glfn->GetUniformLocation (gprog, static_cast("m_matrix")); + if (loc_m != -1) { glfn->UniformMatrix4fv (loc_m, 1, GL_FALSE, this->viewmatrix.arr.data()); } + + // the instance scaling matrix (applied to all instances) + std::int32_t loc_s = glfn->GetUniformLocation (gprog, static_cast("s_matrix")); + if (loc_s != -1) { glfn->UniformMatrix4fv (loc_s, 1, GL_FALSE, this->instscale.arr.data()); } + + if constexpr (debug_render) { + std::cout << "VisualModel::render: scenematrix:\n" << this->scenematrix << std::endl; + std::cout << "VisualModel::render: model viewmatrix:\n" << this->viewmatrix << std::endl; + } + + // Draw the triangles + std::int32_t loc_is = glfn->GetUniformLocation (gprog, static_cast("instance_start")); + std::int32_t loc_ic = glfn->GetUniformLocation (gprog, static_cast("instance_count")); + std::int32_t loc_ipc = glfn->GetUniformLocation (gprog, static_cast("instparam_count")); + if (this->flags.test (vm_bools::instanced)) { + if (loc_is != -1) { glfn->Uniform1i (loc_is, this->instance_start); } + if (loc_ic != -1) { glfn->Uniform1i (loc_ic, this->instance_count); } + if (loc_ipc != -1) { glfn->Uniform1i (loc_ipc, this->instparam_count); } + glfn->DrawElementsInstanced (GL_TRIANGLES, static_cast(this->indices.size()), GL_UNSIGNED_INT, 0, this->instance_count); + } else { + if (loc_is != -1) { glfn->Uniform1i (loc_is, -1); } + if (loc_ic != -1) { glfn->Uniform1i (loc_ic, -1); } + glfn->DrawElements (GL_TRIANGLES, static_cast(this->indices.size()), GL_UNSIGNED_INT, 0); + } + + // Unbind the VAO + glfn->BindVertexArray(0); + + // Do the bounding box optionally + if (this->flags.test (vm_bools::compute_bb) && this->flags.test (vm_bools::show_bb) && !this->indices_bb.empty()) { + glfn->BindVertexArray (this->vao_bb); + glfn->DrawElements (GL_TRIANGLES, static_cast(this->indices_bb.size()), GL_UNSIGNED_INT, 0); + glfn->BindVertexArray(0); + } + } + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + + // Now render any VisualTextModels + if constexpr (mplot::gl::version::gles (glver) == false) { + glfn->PolygonMode (GL_FRONT_AND_BACK, GL_FILL); + } + auto ti = this->texts.begin(); + while (ti != this->texts.end()) { (*ti)->render(); ti++; } + + glfn->UseProgram (prev_shader); + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + } + + //! Setter for the viewmatrix + void setViewMatrix (const sm::mat& mv) { this->viewmatrix = mv; } + //! And a getter + sm::mat getViewMatrix() const { return this->viewmatrix; } + //! Pre or post-multiply + void postmultViewMatrix (const sm::mat& m) { this->viewmatrix = this->viewmatrix * m; } + void premultViewMatrix (const sm::mat& m) { this->viewmatrix = m * this->viewmatrix; } + + //! Scale the viewmatrix (this allows you to 'zoom' your model) + void scaleViewMatrix (const float by) { this->viewmatrix.scale (by); } + + //! An alias for scaleViewMatrix + void set_zoom (const float factor) { this->viewmatrix.scale (factor); } + + //! Reflect your model left to right (across the y-z plane through the origin) + void reflect_x() + { + this->postmultViewMatrix (sm::mat::reflection (sm::vec{}, sm::vec::ux())); + } + + //! Reflect your model up/down (across the x-z plane through the origin) + void reflect_y() + { + this->postmultViewMatrix (sm::mat::reflection (sm::vec{}, sm::vec::uy())); + } + + void reflect_z() + { + this->postmultViewMatrix (sm::mat::reflection (sm::vec{}, sm::vec::uz())); + } + + //! When setting the scene matrix, also have to set the text's scene matrices. + void setSceneMatrix (const sm::mat& sv) + { + this->scenematrix = sv; + this->setSceneMatrixTexts (sv); + } + + //! Set a translation into the scene and into any child texts + template requires (N == 3) || (N == 4) + void setSceneTranslation (const sm::vec& v0) + { + this->scenematrix.set_identity(); + this->scenematrix.translate (v0); + if constexpr (N == 4) { + this->setSceneTranslationTexts (v0.less_one_dim()); + } else { + this->setSceneTranslationTexts (v0); + } + } + + //! Set a translation (only) into the scene view matrix + template requires (N == 3) || (N == 4) + void addSceneTranslation (const sm::vec& v0) { this->scenematrix.pretranslate (v0); } + + //! Set a rotation (only) into the scene view matrix + void setSceneRotation (const sm::quaternion& r) + { + this->scenematrix.set_identity(); + this->scenematrix.rotate (r); + } + + //! Add a rotation to the scene view matrix + void addSceneRotation (const sm::quaternion& r) { this->scenematrix.rotate (r); } + + //! Set a translation to the model view matrix + template requires (N == 3) || (N == 4) + void setViewTranslation (const sm::vec& v0) + { + this->viewmatrix.set_identity(); + this->viewmatrix.translate (v0); + } + + //! Add a translation to the model view matrix + template requires (N == 3) || (N == 4) + void addViewTranslation (const sm::vec& v0) { this->viewmatrix.pretranslate (v0); } + + //! Set a rotation (only) into the view, but keep texts fixed + void setViewRotationFixTexts (const sm::quaternion& r) + { + sm::vec<> os = this->viewmatrix.translation(); + this->viewmatrix.set_identity(); + this->viewmatrix.translate (os); + this->viewmatrix.rotate (r); + } + + //! Set a rotation (only) into the view + void setViewRotation (const sm::quaternion& r) + { + sm::vec<> os = this->viewmatrix.translation(); + this->viewmatrix.set_identity(); + this->viewmatrix.translate (os); + this->viewmatrix.rotate (r); + this->setViewRotationTexts (r); + } + + //! Apply a further rotation to the model view matrix + void addViewRotation (const sm::quaternion& r) + { + this->viewmatrix.rotate (r); + this->addViewRotationTexts (r); + } + + //! Apply a further rotation to the model view matrix, but keep texts fixed + void addViewRotationFixTexts (const sm::quaternion& r) + { + this->viewmatrix.rotate (r); + } + + // The alpha attribute accessors + void setAlpha (const float _a) { this->alpha = _a; } + float getAlpha() const { return this->alpha; } + void incAlpha() + { + this->alpha += 0.1f; + this->alpha = this->alpha > 1.0f ? 1.0f : this->alpha; + } + void decAlpha() + { + this->alpha -= 0.1f; + this->alpha = this->alpha < 0.0f ? 0.0f : this->alpha; + } + + void setGamma (const float _g) { this->gamma = _g; } + float getGamma () const { return this->gamma; } + + // The hide attribute accessors + void setHide (const bool _h = true) { this->flags.set (vm_bools::hide, _h); } + void toggleHide() { this->flags.flip (vm_bools::hide); } + bool hidden() const { return this->flags.test (vm_bools::hide); } + + /* + * Methods used by Visual::savegltf() + */ + + //! Get model translation in a json-friendly string + std::string translation_str() { return this->viewmatrix.translation().str_mat(); } + //! A getter for the viewmatrix translation of the origin (would be same as viewmatrix.translation) + sm::vec get_viewmatrix_origin() const + { + return (this->viewmatrix * sm::vec{0,0,0}).less_one_dim(); + } + + //! The centre of mass of the bounding box may not be the VisualModel's origin + sm::vec get_viewmatrix_bb_centre() const + { + return (this->viewmatrix * this->bb.mid()).less_one_dim(); + } + + //! Apply the viewmatrix to the model's bounding box and return it. You probably don't want + //! this, instead, get_viewmatrix_obb gets the oriented bounding box, and with that you can + //! collision detect with the separarating axis theorem. + sm::interval> get_viewmatrix_modelbb() const + { + sm::interval> vmbb; + vmbb.min = (this->viewmatrix * this->bb.min).less_one_dim(); + vmbb.max = (this->viewmatrix * this->bb.max).less_one_dim(); + return vmbb; + } + + /*! + * Returns a 3x4 matrix whose columns are the vectors obb_centre, obb_x, obb_y and obb_z + * (the half-extent vectors) for the axis aligned bounding box *after* it has been + * transformed (oriented) with the passed in @_viewmatrix. + * + * The returned mat can be passed to Visual::collision_detect(obb1, obb2) + */ + sm::mat get_viewmatrix_obb (const sm::mat& _viewmatrix) const + { + const sm::vec bb_centre = this->bb.mid(); + const sm::vec obb_x_end = (_viewmatrix * (bb_centre + this->bb_x)).less_one_dim(); + const sm::vec obb_y_end = (_viewmatrix * (bb_centre + this->bb_y)).less_one_dim(); + const sm::vec obb_z_end = (_viewmatrix * (bb_centre + this->bb_z)).less_one_dim(); + const sm::vec obb_centre = (_viewmatrix * bb_centre).less_one_dim(); + sm::mat obb; + obb.set_col (0, obb_centre); + obb.set_col (1, obb_x_end - obb_centre); + obb.set_col (2, obb_y_end - obb_centre); + obb.set_col (3, obb_z_end - obb_centre); + return obb; + } + + /*! + * Returns a 3x4 matrix whose columns are the vectors obb_centre, obb_x, obb_y and obb_z for + * the axis aligned bounding box *after* it has been oriented with this model's viewmatrix. + */ + sm::mat get_viewmatrix_obb() const { return this->get_viewmatrix_obb (this->viewmatrix); } + + /*! + * Find collision between this model's oriented bounding box and another oriented bounding box. + */ + bool collision_detect (const sm::mat& obb2) + { + const sm::mat obb1 = this->get_viewmatrix_obb (this->viewmatrix); + return sm::geometry::obb_collision_detect(obb1, obb2); + } + + /*! + * Find collision between this model's oriented bounding box and another model. + */ + bool collision_detect (const VisualModel* mdl2) + { + const sm::mat obb1 = this->get_viewmatrix_obb (this->viewmatrix); + const sm::mat obb2 = mdl2->get_viewmatrix_obb(); + return sm::geometry::obb_collision_detect(obb1, obb2); + } + + //! Return the number of elements in this->indices + std::size_t indices_size() { return this->indices.size(); } + float indices_max() { return this->idx_max; } + float indices_min() { return this->idx_min; } + std::size_t indices_bytes() { return this->indices.size() * sizeof (std::uint32_t); } + //! Return base64 encoded version of indices + std::string indices_base64() + { + std::vector idx_bytes (this->indices.size() << 2, 0); + std::size_t b = 0u; + for (auto i : this->indices) { + idx_bytes[b++] = i & 0xff; + idx_bytes[b++] = i >> 8 & 0xff; + idx_bytes[b++] = i >> 16 & 0xff; + idx_bytes[b++] = i >> 24 & 0xff; + } + return sm::base64::encode (idx_bytes); + } + + /*! + * Find the extents of this VisualModel, returning it as the x range, the y range and the z range. + */ + sm::vec, 3> extents() + { + sm::vec, 3> axis_extents; + for (std::uint32_t i = 0; i < 3; ++i) { axis_extents[i].search_init(); } + for (std::uint32_t j = 0; j < static_cast(this->vertexPositions.size() - 2); j += 3) { + for (std::uint32_t i = 0; i < 3; ++i) { axis_extents[i].update (this->vertexPositions[j+i]); } + } + return axis_extents; + } + + /*! + * Compute the max and min values of indices and vertexPositions/Colors/Normals for use + * when saving gltf files + */ + void computeVertexMaxMins() + { + // Compute index maxmins + for (std::size_t i = 0u; i < this->indices.size(); ++i) { + idx_max = this->indices[i] > idx_max ? this->indices[i] : idx_max; + idx_min = this->indices[i] < idx_min ? this->indices[i] : idx_min; + } + // Check every 0th entry in vertex Positions, every 1st, etc for max in the + + if (this->vertexPositions.size() != this->vertexColors.size() + ||this->vertexPositions.size() != this->vertexNormals.size()) { + throw std::runtime_error ("Expect vertexPositions, Colors and Normals vectors all to have same size"); + } + + for (std::size_t i = 0u; i < this->vertexPositions.size(); i += 3u) { + vpos_maxes[0] = (vertexPositions[i] > vpos_maxes[0]) ? vertexPositions[i] : vpos_maxes[0]; + vpos_maxes[1] = (vertexPositions[i+1] > vpos_maxes[1]) ? vertexPositions[i+1] : vpos_maxes[1]; + vpos_maxes[2] = (vertexPositions[i+2] > vpos_maxes[2]) ? vertexPositions[i+2] : vpos_maxes[2]; + vnorm_maxes[0] = (vertexNormals[i] > vnorm_maxes[0]) ? vertexNormals[i] : vnorm_maxes[0]; + vnorm_maxes[1] = (vertexNormals[i+1] > vnorm_maxes[1]) ? vertexNormals[i+1] : vnorm_maxes[1]; + vnorm_maxes[2] = (vertexNormals[i+2] > vnorm_maxes[2]) ? vertexNormals[i+2] : vnorm_maxes[2]; + + vpos_mins[0] = (vertexPositions[i] < vpos_mins[0]) ? vertexPositions[i] : vpos_mins[0]; + vpos_mins[1] = (vertexPositions[i+1] < vpos_mins[1]) ? vertexPositions[i+1] : vpos_mins[1]; + vpos_mins[2] = (vertexPositions[i+2] < vpos_mins[2]) ? vertexPositions[i+2] : vpos_mins[2]; + vnorm_mins[0] = (vertexNormals[i] < vnorm_mins[0]) ? vertexNormals[i] : vnorm_mins[0]; + vnorm_mins[1] = (vertexNormals[i+1] < vnorm_mins[1]) ? vertexNormals[i+1] : vnorm_mins[1]; + vnorm_mins[2] = (vertexNormals[i+2] < vnorm_mins[2]) ? vertexNormals[i+2] : vnorm_mins[2]; + } + for (std::size_t i = 0u; i < this->vertexPositions.size(); i += this->ncol) { + vcol_maxes[0] = (vertexColors[i] > vcol_maxes[0]) ? vertexColors[i] : vcol_maxes[0]; + vcol_maxes[1] = (vertexColors[i+1] > vcol_maxes[1]) ? vertexColors[i+1] : vcol_maxes[1]; + vcol_maxes[2] = (vertexColors[i+2] > vcol_maxes[2]) ? vertexColors[i+2] : vcol_maxes[2]; + vcol_mins[0] = (vertexColors[i] < vcol_mins[0]) ? vertexColors[i] : vcol_mins[0]; + vcol_mins[1] = (vertexColors[i+1] < vcol_mins[1]) ? vertexColors[i+1] : vcol_mins[1]; + vcol_mins[2] = (vertexColors[i+2] < vcol_mins[2]) ? vertexColors[i+2] : vcol_mins[2]; + } + } + + std::size_t vpos_size() { return this->vertexPositions.size(); } + std::string vpos_max() { return this->vpos_maxes.str_mat(); } + std::string vpos_min() { return this->vpos_mins.str_mat(); } + std::size_t vpos_bytes() { return this->vertexPositions.size() * sizeof (float); } + std::string vpos_base64() + { + std::vector _bytes (this->vertexPositions.size() << 2, 0); + std::size_t b = 0u; + float_bytes fb; + for (auto i : this->vertexPositions) { + fb.f = i; + _bytes[b++] = fb.bytes[0]; + _bytes[b++] = fb.bytes[1]; + _bytes[b++] = fb.bytes[2]; + _bytes[b++] = fb.bytes[3]; + } + return sm::base64::encode (_bytes); + } + std::size_t next_vpos_idx = 0; + void init_vpos_accessor() { this->next_vpos_idx = 0; } + sm::vec get_next_vpos() + { + sm::vec pos; + pos.set_from (std::numeric_limits::max()); + if (this->next_vpos_idx < this->vertexPositions.size()) { + sm::vec tmp = { + this->vertexPositions[this->next_vpos_idx], + this->vertexPositions[this->next_vpos_idx + 1], + this->vertexPositions[this->next_vpos_idx + 2] + }; + + pos = (this->viewmatrix * tmp).less_one_dim(); + this->next_vpos_idx += 3; + } + return pos; + } + + std::size_t vcol_size() { return this->vertexColors.size(); } + std::string vcol_max() { return this->vcol_maxes.str_mat(); } + std::string vcol_min() { return this->vcol_mins.str_mat(); } + std::size_t vcol_bytes() { return this->vertexColors.size() * sizeof (float); } + std::string vcol_base64() + { + std::vector _bytes (this->vertexColors.size() << 2, 0); + std::size_t b = 0u; + float_bytes fb; + for (auto i : this->vertexColors) { + fb.f = i; + _bytes[b++] = fb.bytes[0]; + _bytes[b++] = fb.bytes[1]; + _bytes[b++] = fb.bytes[2]; + _bytes[b++] = fb.bytes[3]; + } + return sm::base64::encode (_bytes); + } + std::size_t vnorm_size() { return this->vertexNormals.size(); } + std::string vnorm_max() { return this->vnorm_maxes.str_mat(); } + std::string vnorm_min() { return this->vnorm_mins.str_mat(); } + std::size_t vnorm_bytes() { return this->vertexNormals.size() * sizeof (float); } + std::string vnorm_base64() + { + std::vector _bytes (this->vertexNormals.size()<<2, 0); + std::size_t b = 0u; + float_bytes fb; + for (auto i : this->vertexNormals) { + fb.f = i; + _bytes[b++] = fb.bytes[0]; + _bytes[b++] = fb.bytes[1]; + _bytes[b++] = fb.bytes[2]; + _bytes[b++] = fb.bytes[3]; + } + return sm::base64::encode (_bytes); + } + std::size_t next_vnorm_idx = 0; + void init_vnorm_accessor() { this->next_vnorm_idx = 0; } + sm::vec get_next_vnorm() + { + sm::vec pos; + pos.set_from (std::numeric_limits::max()); + if (this->next_vnorm_idx < this->vertexPositions.size()) { + pos = { this->vertexPositions[this->next_vnorm_idx], + this->vertexPositions[this->next_vnorm_idx + 1], + this->vertexPositions[this->next_vnorm_idx + 2] }; + this->next_vnorm_idx += 3; + } + return pos; + } + // end Visual::savegltf() methods + + // A VisualModel may be given a name + std::string name = {}; + + //! The current indices index + std::uint32_t idx = 0u; + std::uint32_t idx_bb = 0u; + + /*! + * This is the upper limit for instance_count. We reserve max_isntances of space in the SSBO. + * + * Max number of instances in a model. Each *model* has to reserve space in the SSBOs which + * are managed by VisualResources. VisualResources::max_instances must be larger than this. + */ + std::uint32_t max_instances = 16 * 1024; + //! The offset into the SSBOs for the instance data for this VisualModel + std::uint32_t instance_start = 0; + //! If drawing with instancing, how many instances? <= this->max_instances + std::uint32_t instance_count = 0; + //! If drawing with instancing, how many params will be used (these will be cycled through + //! per-instance and there may be fewer than instance_count parameters) + std::uint32_t instparam_count = 0; + + //! Set the scaling matrix for all instances + void set_instance_scale (const float scl) + { + this->instscale.set_identity(); + this->instscale.scale (scl); + } + + //! Set up the instance positions (with default params for colour, rotn, scale) + void set_instance_data (const sm::vvec>& position) + { + sm::vvec> c = { this->instcolour }; + sm::vvec a = { 1.0f }; + sm::vvec s = { 1.0f }; + this->set_instance_data (position, c, a, s); + } + + //! Set instance positions, with an array containing colour, alpha and scale values to apply + //! to the instances. The size of colour, alpha and scale must match, but it may be of a + //! different size to position. + void set_instance_data (const sm::vvec>& position, const std::array& colour, + const float alpha = 1.0f, const float scale = 1.0f) + { + sm::vvec> c = { colour }; + sm::vvec a = { alpha }; + sm::vvec s = { scale }; + this->set_instance_data (position, c, a, s); + } + + //! Set up the instance positions and params (colour, alpha, scale). Add rotation later on. + void set_instance_data (const sm::vvec>& position, + const sm::vvec>& colour, + const sm::vvec& alpha, const sm::vvec& scale) + { + if (position.size() < 1) { + // Clear data + this->instance_count = 0; + this->instparam_count = 0; + mplot::VisualResources::i().instanced_needs_update (this->parentVis); + return; + } + if (position.size() > this->max_instances) { + std::string ee1 = "set_instance_data: Haven't reserved enough space for that. position.size() = "; + std::string ee2 = std::to_string (position.size()); + std::string ee3 = " > max_instances = "; + std::string ee4 = std::to_string (max_instances); + throw std::runtime_error (ee1 + ee2 + ee3 + ee4); + } + if (colour.size() != scale.size() || colour.size() != alpha.size()) { + throw std::runtime_error ("set_instance_data: params vvecs should all have same size (colour, rotn, scale)"); + } + + for (std::size_t i = 0; i < position.size(); ++i) { + // Get access to the SSBO in VisualResources and add the 3 floats in position[i] at + // the location defined by this->instance_start + i + mplot::VisualResources::i().insert_instance_data (this->instance_start + i, position[i]); + } + this->instance_count = position.size(); + + for (std::size_t i = 0; i < colour.size(); ++i) { + mplot::VisualResources::i().insert_instparam_data (this->instance_start + i, colour[i], alpha[i], scale[i]); + } + this->instparam_count = colour.size(); + + mplot::VisualResources::i().instanced_needs_update (this->parentVis); + } + + //! Setter for the parent ID, parentVis + void set_parent (const std::uint32_t _vis) + { + if (this->parentVis == std::numeric_limits::max()) { this->parentVis = _vis; } + } + + // Flags defaults. + constexpr sm::flags flags_defaults() + { + sm::flags _flags; + _flags.set (vm_bools::postVertexInitRequired, false); + _flags.set (vm_bools::twodimensional, false); + _flags.set (vm_bools::hide, false); + _flags.set (vm_bools::wireframe, false); + _flags.set (vm_bools::greyscale, false); + _flags.set (vm_bools::show_bb, false); + _flags.set (vm_bools::compute_bb, true); + return _flags; + } + + // State/options flags + sm::flags flags = flags_defaults(); + + // Setters for flags + void show_bb (const bool val) { this->flags.set (vm_bools::show_bb, val); } + void compute_bb (const bool val) { this->flags.set (vm_bools::compute_bb, val); } + + /*! + * An interval can be used for an axis-aligned bounding box for this VisualModel. You can + * get the centre with bb.mid(). + */ + sm::interval> bb; + std::array colour_bb = mplot::colour::grey90; + // Bounding box half-extent vectors (which can be converted into an oriented bb with the viewmatrix) + sm::vec bb_x = {}; + sm::vec bb_y = {}; + sm::vec bb_z = {}; + + void twodimensional (const bool val) { this->flags.set (vm_bools::twodimensional, val); } + bool twodimensional() const { return this->flags.test (vm_bools::twodimensional); } + + // Wireframe rendering is not aviailable on GL ES + template requires (mplot::gl::version::gles (glver) == false) + void wireframe (const bool val) { this->flags.set (vm_bools::wireframe, val); } + template requires (mplot::gl::version::gles (glver) == false) + bool wireframe() const { return this->flags.test (vm_bools::wireframe); } + + void greyscale (const bool val) { this->flags.set (vm_bools::greyscale, val); } + bool greyscale() const { return this->flags.test (vm_bools::greyscale); } + + void instanced (const bool val) { this->flags.set (vm_bools::instanced, val); } + bool instanced() const { return this->flags.test (vm_bools::instanced); } + + //! Getter for vertex positions (for mplot::NormalsVisual) + std::vector getVertexPositions() { return this->vertexPositions; } + //! Getter for vertex normals (for mplot::NormalsVisual) + std::vector getVertexNormals() { return this->vertexNormals; } + std::vector getVertexColors() { return this->vertexColors; } + + // A vector of meshgroups to be appended to the end of this VisualModel. The vertices in + // these meshgroups are added after the call to initializeVertices. + std::vector extra_meshgroups; + + // Add a meshgroup by pointer. These are appended at the end of initializeVertices + void addMeshgroup (const mplot::meshgroup& mg) { this->extra_meshgroups.push_back (mg); } + + protected: + + //! The model-specific view matrix. Used to transform the pose of the model in the scene. + sm::mat viewmatrix = sm::mat::identity(); + /*! + * The scene view matrix. Each VisualModel has a copy of the scenematrix. It's set in + * Visual::render. Different VisualModels may have different scenematrices (for example, the + * CoordArrows has a different scenematrix from other VisualModels, and models marked + * 'twodimensional' also have a different scenematrix). + */ + sm::mat scenematrix = sm::mat::identity(); + + /*! + * Instance scaling. This matrix can be used to control the scale of all instances of an + * instanced VisualModel + */ + sm::mat instscale = sm::mat::identity(); + + /*! + * The colour for all instances. This is used if you don't set colour in your instance params. + */ + std::array instcolour = mplot::colour::yellow; + + //! Contains the positions within the vbo array of the different vertex buffer objects + enum VBOPos { posnVBO, normVBO, colVBO, idxVBO, numVBO }; + + /* + * Compute positions and colours of vertices for the hexes and store in these: + */ + + //! The OpenGL Vertex Array Object + std::uint32_t vao = 0; + + //! Vertex Buffer Objects stored in an array + std::unique_ptr vbos; + + //! CPU-side data for indices + std::vector indices = {}; + //! CPU-side data for vertex positions + std::vector vertexPositions = {}; + //! CPU-side data for vertex normals + std::vector vertexNormals = {}; + //! CPU-side data for vertex colours + std::vector vertexColors = {}; + + //! Number of elements in a colour (if 4, then last element is alpha) + std::uint32_t ncol = 3; + + // OpenGL arrays for the bounding box, if needed + std::uint32_t vao_bb = 0; + std::unique_ptr vbos_bb; + std::vector indices_bb = {}; + std::vector vpos_bb = {}; + std::vector vnorm_bb = {}; + std::vector vcol_bb = {}; + + static constexpr float _max = std::numeric_limits::max(); + static constexpr float _low = std::numeric_limits::lowest(); + + // The max and min values in the next 8 attributes are only computed if gltf files are going + // to be output by Visual::savegltf() + + //! Max values of 0th, 1st and 2nd coordinates in vertexPositions + sm::vec vpos_maxes = { _low, _low, _low }; // fixme: same as bounding box! + //! Min values in vertexPositions + sm::vec vpos_mins = { _max, _max, _max }; + sm::vec vcol_maxes = { _low, _low, _low }; + sm::vec vcol_mins = { _max, _max, _max }; + sm::vec vnorm_maxes = { _low, _low, _low }; + sm::vec vnorm_mins = { _max, _max, _max }; + //! Max value in indices + std::uint32_t idx_max = 0u; + //! Min value in indices. + std::uint32_t idx_min = std::numeric_limits::max(); + + //! A model-wide alpha value for the shader + float alpha = 1.0f; + + //! A per-model gamma value to interpret the colours in the model. Applied in the vertex shader. + float gamma = 1.0f; + + // The mplot::VisualBase in which this model exists. + std::uint32_t parentVis = std::numeric_limits::max(); + + //! A vector of pointers to text models that should be rendered. + std::vector>> texts; + + //! Set up a vertex buffer object - bind, buffer and set vertex array object + //! attribute. n_dims = 3 for position, normal, 3 or 4 for colour. + void setupVBO (std::uint32_t& buf, std::vector& dat, std::uint32_t bufferAttribPosition, std::uint32_t n_dims) + { + std::size_t sz = dat.size() * sizeof(float); + + if (this->parentVis == std::numeric_limits::max()) { + throw std::runtime_error ("parentVis is unset"); + } + GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + glfn->BindBuffer (GL_ARRAY_BUFFER, buf); + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + glfn->BufferData (GL_ARRAY_BUFFER, sz, dat.data(), GL_STATIC_DRAW); + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + glfn->VertexAttribPointer (bufferAttribPosition, n_dims, GL_FLOAT, GL_FALSE, 0, (void*)(0)); + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + glfn->EnableVertexAttribArray (bufferAttribPosition); + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + } + + //! Push three floats onto the vector of floats \a vp + void vertex_push (const float& x, const float& y, const float& z, std::vector& vp) + { + vp.emplace_back (x); + vp.emplace_back (y); + vp.emplace_back (z); + } + //! Push four floats onto the vector of floats \a vp + void vertex_push (const float& x, const float& y, const float& z, const float& w, std::vector& vp) + { + vp.emplace_back (x); + vp.emplace_back (y); + vp.emplace_back (z); + vp.emplace_back (w); + } + //! Push array of 3 floats onto the vector of floats \a vp N is the number of dimensions in + //! the passed in normal or position arr, but only 3 are ever stored. + template requires (N == 3 || N == 4) + void vertex_push (const std::array& arr, std::vector& vp) + { + vp.emplace_back (arr[0]); + vp.emplace_back (arr[1]); + vp.emplace_back (arr[2]); + // Ignore any fourth element + } + //! Push sm::vec of 3 floats onto the vector of floats \a vp + template requires (N == 3 || N == 4) + void vertex_push (const sm::vec& vec, std::vector& vp) + { + vp.emplace_back (vec[0]); + vp.emplace_back (vec[1]); + vp.emplace_back (vec[2]); + // Ignore any fourth element + } + template requires (N == 3 || N == 4) + void vertex_push_colour (const std::array& arr, std::vector& vp) + { + vp.emplace_back (arr[0]); + vp.emplace_back (arr[1]); + vp.emplace_back (arr[2]); + // For colour, fourth element may be alpha + if (this->ncol == 4) { + if constexpr (N == 4) { + vp.emplace_back (arr[3]); + } else { + vp.emplace_back (1.0f); + } + } + } + //! Push sm::vec of 3 floats onto the vector of floats \a vp + template requires (N == 3 || N == 4) + void vertex_push_colour (const sm::vec& vec, std::vector& vp) + { + vp.emplace_back (vec[0]); + vp.emplace_back (vec[1]); + vp.emplace_back (vec[2]); + if (this->ncol == 4) { + if constexpr (N == 4) { + vp.emplace_back (vec[3]); + } else { + vp.emplace_back (1.0f); + } + } + } + + /*! + * Add the given meshgroup to this VisualModel + */ + void computeMeshgroup (const mplot::meshgroup& mg) + { + mg.validate(); + + bool single_colr = mg.colours.empty(); + for (std::uint32_t i = 0; i < mg.positions.size(); ++i) { + // We apply mg.transform *here*, rather than writing it into the viewmatrix. This is + // because other elements of this visual model may be added with the assumption of an + // identity viewmatrix. + this->vertex_push (mg.transform * mg.positions[i], this->vertexPositions); + this->vertex_push (mg.transform * mg.normals[i], this->vertexNormals); + if (single_colr) { + this->vertex_push_colour (mg.single_colour, this->vertexColors); + } else { + this->vertex_push_colour (mg.colours[i], this->vertexColors); + } + } + for (std::uint32_t i = 0; i < mg.indices.size(); ++i) { + this->indices.push_back (mg.indices[i] + this->idx); + } + this->idx += mg.positions.size(); + } + + /** + * START vertex/index computation code + * + * ALL methods below this point are for computing vertices. + * + * The metheds compute vertexPositions/Normals/Colors along with indices in a form suitable + * for use with GL's DrawElements (or DrawElementsInstanced) drawing call. + */ + + /*! + * Create a tube from \a start to \a end, with radius \a r and a colour which + * transitions from the colour \a colStart to \a colEnd. + * + * This version simply sub-calls into computeFlaredTube which will randomly choose the angle + * of the vertices around the centre of each end cap. + * + * \param idx The index into the 'vertex array' + * \param start The start of the tube + * \param end The end of the tube + * \param colStart The tube starting colour + * \param colEnd The tube's ending colour + * \param r Radius of the tube + * \param segments Number of segments used to render the tube + */ + void computeTube (sm::vec start, sm::vec end, + std::array colStart, std::array colEnd, + float r = 1.0f, std::int32_t segments = 12) + { + this->computeFlaredTube (start, end, colStart, colEnd, r, r, segments); + } + + /*! + * Compute a tube. This version requires unit vectors for orientation of the + * tube end faces/vertices (useful for graph markers). The other version uses a + * randomly chosen vector to do this. + * + * Create a tube from \a start to \a end, with radius \a r and a colour which + * transitions from the colour \a colStart to \a colEnd. + * + * \param start The start of the tube + * \param end The end of the tube + * \param _ux a vector in the x axis direction for the end face + * \param _uy a vector in the y axis direction. _ux ^ _uy gives the end cap normal + * \param colStart The tube starting colour + * \param colEnd The tube's ending colour + * \param r Radius of the tube + * \param segments Number of segments used to render the tube + * \param rotation A rotation in the _ux/_uy plane to orient the vertices of the + * tube. Useful if this is to be a short tube used as a graph marker. + * \param bb If true, write into the bounding box arrays, not the main ones + */ + void computeTube (sm::vec start, sm::vec end, + sm::vec _ux, sm::vec _uy, + std::array colStart, std::array colEnd, + float r = 1.0f, std::int32_t segments = 12, float rotation = 0.0f, bool bb = false) + { + // The vector from start to end defines direction of the tube + sm::vec vstart = start; + sm::vec vend = end; + + // v is a face normal + sm::vec v = _ux.cross(_uy); + v.renormalize(); + + // If bounding box, populate different buffers: + std::vector& vp = bb ? this->vpos_bb : this->vertexPositions; + std::vector& vn = bb ? this->vnorm_bb : this->vertexNormals; + std::vector& vc = bb ? this->vcol_bb : this->vertexColors; + std::vector& idcs = bb ? this->indices_bb : this->indices; + std::uint32_t& _idx = bb ? this->idx_bb : this->idx; + + // Push the central point of the start cap - this is at location vstart + this->vertex_push (vstart, vp); + this->vertex_push (-v, vn); + this->vertex_push_colour (colStart, vc); + + // Start cap vertices (a triangle fan) + for (std::int32_t j = 0; j < segments; j++) { + // t is the angle of the segment + float t = rotation + j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; + this->vertex_push (vstart+c, vp); + this->vertex_push (-v, vn); + this->vertex_push_colour (colStart, vc); + } + + // Intermediate, near start cap. Normals point in direction c + for (std::int32_t j = 0; j < segments; j++) { + float t = rotation + j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; + this->vertex_push (vstart+c, vp); + c.renormalize(); + this->vertex_push (c, vn); + this->vertex_push_colour (colStart, vc); + } + + // Intermediate, near end cap. Normals point in direction c + for (std::int32_t j = 0; j < segments; j++) { + float t = rotation + (float)j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; + this->vertex_push (vend+c, vp); + c.renormalize(); + this->vertex_push (c, vn); + this->vertex_push_colour (colEnd, vc); + } + + // Bottom cap vertices + for (std::int32_t j = 0; j < segments; j++) { + float t = rotation + (float)j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; + this->vertex_push (vend+c, vp); + this->vertex_push (v, vn); + this->vertex_push_colour (colEnd, vc); + } + + // Bottom cap. Push centre vertex as the last vertex. + this->vertex_push (vend, vp); + this->vertex_push (v, vn); + this->vertex_push_colour (colEnd, vc); + + // Number of vertices = segments * 4 + 2. + std::int32_t nverts = (segments * 4) + 2; + + // After creating vertices, push all the indices. + std::uint32_t capMiddle = _idx; + std::uint32_t capStartIdx = _idx + 1u; + std::uint32_t endMiddle = _idx + static_cast(nverts) - 1u; + std::uint32_t endStartIdx = capStartIdx + (3u * segments); + + // Start cap indices + for (std::int32_t j = 0; j < segments-1; j++) { + idcs.push_back (capMiddle); + idcs.push_back (capStartIdx + j); + idcs.push_back (capStartIdx + 1 + j); + } + // Last one + idcs.push_back (capMiddle); + idcs.push_back (capStartIdx + segments - 1); + idcs.push_back (capStartIdx); + + // Middle sections + for (std::int32_t lsection = 0; lsection < 3; ++lsection) { + capStartIdx = _idx + 1 + lsection*segments; + endStartIdx = capStartIdx + segments; + for (std::int32_t j = 0; j < segments; j++) { + idcs.push_back (capStartIdx + j); + if (j == (segments-1)) { + idcs.push_back (capStartIdx); + } else { + idcs.push_back (capStartIdx + 1 + j); + } + idcs.push_back (endStartIdx + j); + idcs.push_back (endStartIdx + j); + if (j == (segments-1)) { + idcs.push_back (endStartIdx); + } else { + idcs.push_back (endStartIdx + 1 + j); + } + if (j == (segments-1)) { + idcs.push_back (capStartIdx); + } else { + idcs.push_back (capStartIdx + j + 1); + } + } + } + + // bottom cap + for (std::int32_t j = 0; j < segments-1; j++) { + idcs.push_back (endMiddle); + idcs.push_back (endStartIdx + j); + idcs.push_back (endStartIdx + 1 + j); + } + idcs.push_back (endMiddle); + idcs.push_back (endStartIdx + segments - 1); + idcs.push_back (endStartIdx); + + // Update idx + _idx += nverts; + } // end computeTube with ux/uy vectors for faces + + /*! + * A 'draw an arrow' primitive. This is a 3D, tubular arrow made of a tube and a cone. + * + * \param start Start coordinate of the arrow + * + * \param end End coordinate of the arrow + * + * \param clr The colour for the arrow + * + * \param tube_radius Radius of arrow shaft. If < 0, then set from (end-start).length() + * + * \param arrowhead_prop The proportion of the arrow length that the head should take up + * + * \param cone_radius Radisu of cone that make the arrow head. If < 0, then set from + * tube_radius + * + * \param shapesides How many facets to draw tube/cone with + */ + void computeArrow (const sm::vec& start, const sm::vec& end, + const std::array clr, + float tube_radius = -1.0f, + float arrowhead_prop = -1.0f, + float cone_radius = -1.0f, + const std::int32_t shapesides = 18) + { + // The right way to draw an arrow. + sm::vec arrow_line = end - start; + float len = arrow_line.length(); + // Unless client code specifies, compute tube radius from length of arrow + if (tube_radius < 0.0f) { tube_radius = len / 40.0f; } + if (arrowhead_prop < 0.0f) { arrowhead_prop = 0.15f; } + if (cone_radius < 0.0f) { cone_radius = 1.75f * tube_radius; } + // We don't draw the full tube + sm::vec cone_start = arrow_line.shorten (len * arrowhead_prop); + cone_start += start; + this->computeTube (start, cone_start, clr, clr, tube_radius, shapesides); + float conelen = (end-cone_start).length(); + if (arrow_line.length() > conelen) { + this->computeCone (cone_start, end, 0.0f, clr, cone_radius, shapesides); + } + } + + /*! + * Create a flared tube from \a start to \a end, with radius \a r at the start and a colour + * which transitions from the colour \a colStart to \a colEnd. The radius of the end is + * determined by the given angle, flare, in radians. + * + * \param idx The index into the 'vertex array' + * \param start The start of the tube + * \param end The end of the tube + * \param colStart The tube starting colour + * \param colEnd The tube's ending colour + * \param r Radius of the tube + * \param segments Number of segments used to render the tube + * \param flare The angle, measured wrt the direction of the tube in radians, by which the + * tube 'flares' + */ + void computeFlaredTube (sm::vec start, sm::vec end, + std::array colStart, std::array colEnd, + float r = 1.0f, std::int32_t segments = 12, float flare = 0.0f) + { + // Find the length of the tube + sm::vec v = end - start; + float l = v.length(); + // Compute end radius from the length and the flare angle: + float r_add = l * std::tan (std::abs(flare)) * (flare > 0.0f ? 1.0f : -1.0f); + float r_end = r + r_add; + // Now call into the other overload: + this->computeFlaredTube (start, end, colStart, colEnd, r, r_end, segments); + } + + /*! + * Create a flared tube from \a start to \a end, with radius \a r at the start and a colour + * which transitions from the colour \a colStart to \a colEnd. The radius of the end is + * r_end, given as a function argument. + * + * \param start The start of the tube + * \param end The end of the tube + * \param colStart The tube starting colour + * \param colEnd The tube's ending colour + * \param r Radius of the tube's start cap + * \param r_end radius of the end cap + * \param segments Number of segments used to render the tube + */ + void computeFlaredTube (sm::vec start, sm::vec end, + std::array colStart, std::array colEnd, + float r = 1.0f, float r_end = 1.0f, std::int32_t segments = 12) + { + // The vector from start to end defines a vector and a plane. Find a + // 'circle' of points in that plane. + sm::vec vstart = start; + sm::vec vend = end; + sm::vec v = vend - vstart; + v.renormalize(); + + // circle in a plane defined by a point (v0 = vstart or vend) and a normal + // (v) can be found: Choose random vector vr. A vector inplane = vr ^ v. The + // unit in-plane vector is inplane.normalise. Can now use that vector in the + // plan to define a point on the circle. Note that this starting point on + // the circle is at a random position, which means that this version of + // computeTube is useful for tubes that have quite a few segments. + sm::vec rand_vec; + rand_vec.randomize(); + sm::vec inplane = rand_vec.cross(v); + inplane.renormalize(); + + // Now use parameterization of circle inplane = p1-x1 and + // c1(t) = ( (p1-x1).normalized std::sin(t) + v.normalized cross (p1-x1).normalized * std::cos(t) ) + // c1(t) = ( inplane std::sin(t) + v * inplane * std::cos(t) + sm::vec v_x_inplane = v.cross(inplane); + + // Push the central point of the start cap - this is at location vstart + this->vertex_push (vstart, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (colStart, this->vertexColors); + + // Start cap vertices. Draw as a triangle fan, but record indices so that we + // only need a single call to glDrawElements. + for (std::int32_t j = 0; j < segments; j++) { + // t is the angle of the segment + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; + this->vertex_push (vstart+c, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (colStart, this->vertexColors); + } + + // Intermediate, near start cap. Normals point in direction c + for (std::int32_t j = 0; j < segments; j++) { + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; + this->vertex_push (vstart+c, this->vertexPositions); + c.renormalize(); + this->vertex_push (c, this->vertexNormals); + this->vertex_push_colour (colStart, this->vertexColors); + } + + // Intermediate, near end cap. Normals point in direction c + for (std::int32_t j = 0; j < segments; j++) { + float t = (float)j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r_end + v_x_inplane * std::cos(t) * r_end; + this->vertex_push (vend+c, this->vertexPositions); + c.renormalize(); + this->vertex_push (c, this->vertexNormals); + this->vertex_push_colour (colEnd, this->vertexColors); + } + + // Bottom cap vertices + for (std::int32_t j = 0; j < segments; j++) { + float t = (float)j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r_end + v_x_inplane * std::cos(t) * r_end; + this->vertex_push (vend+c, this->vertexPositions); + this->vertex_push (v, this->vertexNormals); + this->vertex_push_colour (colEnd, this->vertexColors); + } + + // Bottom cap. Push centre vertex as the last vertex. + this->vertex_push (vend, this->vertexPositions); + this->vertex_push (v, this->vertexNormals); + this->vertex_push_colour (colEnd, this->vertexColors); + + // Note: number of vertices = segments * 4 + 2. + std::int32_t nverts = (segments * 4) + 2; + + // After creating vertices, push all the indices. + std::uint32_t capMiddle = this->idx; + std::uint32_t capStartIdx = this->idx + 1u; + std::uint32_t endMiddle = this->idx + static_cast(nverts) - 1u; + std::uint32_t endStartIdx = capStartIdx + (3u * segments); + + // Start cap + for (std::int32_t j = 0; j < segments-1; j++) { + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + j); + this->indices.push_back (capStartIdx + 1 + j); + } + // Last one + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + segments - 1); + this->indices.push_back (capStartIdx); + + // Middle sections + for (std::int32_t lsection = 0; lsection < 3; ++lsection) { + capStartIdx = this->idx + 1 + lsection*segments; + endStartIdx = capStartIdx + segments; + // This does sides between start and end. I want to do this three times. + for (std::int32_t j = 0; j < segments; j++) { + // Triangle 1 + this->indices.push_back (capStartIdx + j); + if (j == (segments-1)) { + this->indices.push_back (capStartIdx); + } else { + this->indices.push_back (capStartIdx + 1 + j); + } + this->indices.push_back (endStartIdx + j); + // Triangle 2 + this->indices.push_back (endStartIdx + j); + if (j == (segments-1)) { + this->indices.push_back (endStartIdx); + } else { + this->indices.push_back (endStartIdx + 1 + j); + } + if (j == (segments-1)) { + this->indices.push_back (capStartIdx); + } else { + this->indices.push_back (capStartIdx + j + 1); + } + } + } + + // Bottom cap + for (std::int32_t j = 0; j < segments-1; j++) { + this->indices.push_back (endMiddle); + this->indices.push_back (endStartIdx + j); + this->indices.push_back (endStartIdx + 1 + j); + } + // Last one + this->indices.push_back (endMiddle); + this->indices.push_back (endStartIdx + segments - 1); + this->indices.push_back (endStartIdx); + + // Update idx + this->idx += nverts; + } // end computeFlaredTube with randomly initialized end vertices + + /*! + * Create an open (no end caps) flared tube from \a start to \a end, with radius + * \a r at the start and a colour which transitions from the colour \a colStart + * to \a colEnd. The radius of the end is r_end, given as a function argument. + * + * This has a normal vector for the start and end of the tube, so that the + * circles can be angled. + * + * \param start The start of the tube + * \param end The end of the tube + * \param colStart The tube starting colour + * \param colEnd The tube's ending colour + * \param n_start The normal of the start 'face' + * \param n_end The normal of the end 'face' + * + * \param z_start A vector pointing to the first vertex on the tube. allows + * orientation of tube faces for connected tubes (which is what this primitive + * is all about) + * + * \param r Radius of the tube's start circle + * \param r_end radius of the end circle + * \param segments Number of segments used to render the tube + */ + void computeOpenFlaredTube (sm::vec start, sm::vec end, + sm::vec n_start, sm::vec n_end, + std::array colStart, std::array colEnd, + float r = 1.0f, float r_end = 1.0f, std::int32_t segments = 12) + { + // The vector from start to end defines a vector and a plane. Find a + // 'circle' of points in that plane. + sm::vec vstart = start; + sm::vec vend = end; + sm::vec v = vend - vstart; + v.renormalize(); + + // Two rotations about our face normals + sm::quaternion rotn_start (n_start, sm::mathconst::pi_over_2); + sm::quaternion rotn_end (-n_end, sm::mathconst::pi_over_2); + + sm::vec inplane = v.cross (n_start); + // The above is no good if n_start and v are colinear. In that case choose random inplane: + if (inplane.length() < std::numeric_limits::epsilon()) { + sm::vec rand_vec; + rand_vec.randomize(); + inplane = rand_vec.cross(v); + } + inplane.renormalize(); + + // inplane defines a plane, n_start defines a plane. Our first point is the + // intersection of the two planes and the circle of the end. + sm::vec v_x_inplane = n_start.cross (inplane);// rotn_start * inplane; + v_x_inplane.renormalize(); + + // If r == r_end we want a circular cross section tube (and not an elliptical cross section). + float r_mod = r / v_x_inplane.cross (v).length(); + + // Start ring of vertices. Normals point in direction c + // Now use parameterization of circle inplane = p1-x1 and + // c1(t) = ( (p1-x1).normalized std::sin(t) + v.normalized cross (p1-x1).normalized * std::cos(t) ) + // c1(t) = ( inplane std::sin(t) + v * inplane * std::cos(t) + for (std::int32_t j = 0; j < segments; j++) { + float t = static_cast(j) * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r_mod; + this->vertex_push (vstart + c, this->vertexPositions); + c.renormalize(); + this->vertex_push (c, this->vertexNormals); + this->vertex_push_colour (colStart, this->vertexColors); + } + + // end ring of vertices. Normals point in direction c + v_x_inplane = inplane.cross (n_end); + v_x_inplane.renormalize(); + r_mod = r_end / v_x_inplane.cross (v).length(); + + for (std::int32_t j = 0; j < segments; j++) { + float t = static_cast(j) * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r_end + v_x_inplane * std::cos(t) * r_mod; + this->vertex_push (vend + c, this->vertexPositions); + c.renormalize(); + this->vertex_push (c, this->vertexNormals); + this->vertex_push_colour (colEnd, this->vertexColors); + } + + // Number of vertices + std::int32_t nverts = (segments * 2); + + // After creating vertices, push all the indices. + std::uint32_t sIdx = this->idx; + std::uint32_t eIdx = sIdx + segments; + // This does sides between start and end + for (std::int32_t j = 0; j < segments; j++) { + // Triangle 1 + this->indices.push_back (sIdx + j); + if (j == (segments-1)) { + this->indices.push_back (sIdx); + } else { + this->indices.push_back (sIdx + 1 + j); + } + this->indices.push_back (eIdx + j); + // Triangle 2 + this->indices.push_back (eIdx + j); + if (j == (segments-1)) { + this->indices.push_back (eIdx); + } else { + this->indices.push_back (eIdx + 1 + j); + } + if (j == (segments-1)) { + this->indices.push_back (sIdx); + } else { + this->indices.push_back (sIdx + j + 1); + } + } + + // Update idx + this->idx += nverts; + } // end computeOpenFlaredTube + + // An open, but un-flared tube with no end caps + void computeOpenTube (sm::vec start, sm::vec end, + sm::vec n_start, sm::vec n_end, + std::array colStart, std::array colEnd, + float r = 1.0f, std::int32_t segments = 12) + { + this->computeOpenFlaredTube (start, end, n_start, n_end, colStart, colEnd, r, r, segments); + } + + + void computeFlatQuad (sm::vec c1, sm::vec c2, + sm::vec c3, sm::vec c4, + std::array col) + { + this->computeFlatQuad (c1.less_one_dim(), c2.less_one_dim(), c3.less_one_dim(), c4.less_one_dim(), col); + } + + //! Compute a Quad from 4 arbitrary corners which must be ordered clockwise around the quad. + void computeFlatQuad (sm::vec c1, sm::vec c2, + sm::vec c3, sm::vec c4, + std::array col) + { + // v is the face normal + sm::vec u1 = c1-c2; + sm::vec u2 = c2-c3; + sm::vec v = u2.cross(u1); + v.renormalize(); + + // Push corner vertices + std::size_t vpsz = this->vertexPositions.size(); + this->vertexPositions.resize (vpsz + 12); + for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c1[i]; } + for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c2[i]; } + for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c3[i]; } + for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c4[i]; } + + // Colours/normals + std::size_t vcsz = this->vertexColors.size(); + std::size_t vnsz = this->vertexNormals.size(); + this->vertexColors.resize (vcsz + 12); + this->vertexNormals.resize (vnsz + 12); + for (std::uint32_t i = 0; i < 4u; ++i) { + for (std::uint32_t j = 0; j < 3u; ++j) { + this->vertexColors[vcsz++] = col[j]; + this->vertexNormals[vnsz++] = v[j]; + } + // Alpha 1 as incoming colour does not have alpha + if (this->ncol == 4) { this->vertexColors[vcsz++] = 1.0f; } + } + + std::size_t i0 = this->indices.size(); + this->indices.resize (i0 + 6, 0); + this->indices[i0++] = this->idx; + this->indices[i0++] = this->idx + 2; + this->indices[i0++] = this->idx + 1; + this->indices[i0++] = this->idx; + this->indices[i0++] = this->idx + 3; + this->indices[i0++] = this->idx + 2; + + this->idx += 4; + } + + /*! + * Compute a flat polygon. + * + * Create a flat polygon with segments outer edges. Radius \a r and colour \a col. + * + * \param vstart The centre of the polygon + * \param _ux a vector in the x axis direction for the end face + * \param _uy a vector in the y axis direction. If not same length as _ux, distortions will be seen + * \param col The polygon colour + * \param r Radius + * \param segments Number of segments used to render the polygon + * \param rotation A rotation in the ux/uy plane to orient the vertices of the polygon. + */ + void computeFlatPoly (sm::vec vstart, + sm::vec _ux, sm::vec _uy, + std::array col, + float r = 1.0f, std::int32_t segments = 12, float rotation = 0.0f) + { + // v is a face normal + sm::vec v = _uy.cross(_ux); + v.renormalize(); + + // Push the central point of the start cap - this is at location vstart + this->vertex_push (vstart, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + // Polygon vertices (a triangle fan) + for (std::int32_t j = 0; j < segments; j++) { + // t is the angle of the segment + float t = rotation + j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; + this->vertex_push (vstart+c, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + } + + // Number of vertices + std::int32_t nverts = segments + 1; + + // After creating vertices, push all the indices. + std::uint32_t capMiddle = this->idx; + std::uint32_t capStartIdx = this->idx + 1; + + // Start cap indices + for (std::int32_t j = 0; j < segments-1; j++) { + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + j); + this->indices.push_back (capStartIdx + 1 + j); + } + // Last one + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + segments - 1); + this->indices.push_back (capStartIdx); + + // Update idx + this->idx += nverts; + } // end computeFlatPoly with ux/uy vectors for faces + + void computeFlatPoly (sm::vec vcentre, + sm::vec _normal, + std::array col, + float r = 1.0f, std::int32_t segments = 12) + { + // Find random _ux given _normal. + _normal.renormalize(); + sm::vec rand_vec; + rand_vec.randomize(); + sm::vec inplane1 = rand_vec.cross (_normal); + inplane1.renormalize(); + sm::vec inplane2 = _normal.cross (inplane1); + this->computeFlatPoly (vcentre, inplane1, inplane2, col, r, segments, 0.0f); + } + + /*! + * Make a ring of radius r, comprised of flat segments + * + * \param ro position of the centre of the ring + * \param rc The ring colour. + * \param r Radius of the ring + * \param t Thickness of the ring + * \param segments Number of tube segments used to render the ring + * \param tfm a transform to apply to the points + */ + void computeRing (sm::vec ro, std::array rc, float r = 1.0f, + float t = 0.1f, std::int32_t segments = 12, + const sm::mat tfm = sm::mat::identity()) + { + float r_in = r - (t * 0.5f); + float r_out = r + (t * 0.5f); + this->computeRingInOut (ro, rc, r_in, r_out, segments, tfm); + } + + /*! + * Make a ring of radius r, comprised of flat segments, specifying inner and outer radii + * + * \param ro position of the centre of the ring + * \param rc The ring colour. + * \param r_in Inner radius of the ring + * \param r_out Outer radius of the ring + * \param segments Number of tube segments used to render the ring + * \param tfm a transform to apply to the points + */ + void computeRingInOut (sm::vec ro, std::array rc, + float r_in = 1.0f, float r_out = 2.0f, std::int32_t segments = 12, + const sm::mat tfm = sm::mat::identity()) + { + for (std::int32_t j = 0; j < segments; j++) { + float segment = sm::mathconst::two_pi * static_cast(j) / segments; + // x and y of inner point + float xin = r_in * std::cos (segment); + float yin = r_in * std::sin (segment); + float xout = r_out * std::cos (segment); + float yout = r_out * std::sin (segment); + std::int32_t segjnext = (j + 1) % segments; + float segnext = sm::mathconst::two_pi * static_cast(segjnext) / segments; + float xin_n = r_in * std::cos (segnext); + float yin_n = r_in * std::sin (segnext); + float xout_n = r_out * std::cos (segnext); + float yout_n = r_out * std::sin (segnext); + + // Now draw a quad + sm::vec c4 = { xin, yin, 0.0f }; + sm::vec c3 = { xout, yout, 0.0f }; + sm::vec c2 = { xout_n, yout_n, 0.0f }; + sm::vec c1 = { xin_n, yin_n, 0.0f }; + this->computeFlatQuad (tfm * (ro + c1), tfm * (ro + c2), tfm * (ro + c3), tfm * (ro + c4), rc); + } + } + + /*! + * Make a ring of radius r, comprised of flat segments + * + * \param ro position of the centre of the ring + * \param rc The ring colour. + * \param mc The mark colour. + * \param m_centre The centre angle of the mark. + * \param r Radius of the ring + * \param t Thickness of the ring + * \param segments Number of tube segments used to render the ring + * \param tfm a transform to apply to the points + */ + void computeMarkedRing (sm::vec ro, std::array rc, + std::array mc, + float m_centre = 0.0f, + float r = 1.0f, + float t = 0.1f, std::int32_t segments = 12, + const sm::mat tfm = sm::mat::identity()) + { + float r_in = r - (t * 0.5f); + float r_out = r + (t * 0.5f); + this->computeMarkedRingInOut (ro, rc, mc, m_centre, r_in, r_out, segments, tfm); + } + + /*! + * Make a ring of radius r, comprised of flat segments, specifying inner and outer radii, + * which has a section coloured in a second colour. + * + * \param ro position of the centre of the ring + * \param rc The ring colour. + * \param mc The mark colour. + * \param m_centre The centre angle of the mark. + * \param m_num_segs The number of segments to colour either size of the centre angle. + * \param r_in Inner radius of the ring + * \param r_out Outer radius of the ring + * \param segments Number of tube segments used to render the ring + * \param tfm a transform to apply to the points + */ + void computeMarkedRingInOut (sm::vec ro, std::array rc, + std::array mc, float m_centre = 0.0f, + float r_in = 1.0f, float r_out = 2.0f, std::int32_t segments = 12, + const sm::mat tfm = sm::mat::identity()) + { + for (std::int32_t j = 0; j < segments; j++) { + float segment = sm::mathconst::two_pi * static_cast(j) / segments; + // x and y of inner point + float xin = r_in * std::cos (segment); + float yin = r_in * std::sin (segment); + float xout = r_out * std::cos (segment); + float yout = r_out * std::sin (segment); + std::int32_t segjnext = (j + 1) % segments; + float segnext = sm::mathconst::two_pi * static_cast(segjnext) / segments; + float xin_n = r_in * std::cos (segnext); + float yin_n = r_in * std::sin (segnext); + float xout_n = r_out * std::cos (segnext); + float yout_n = r_out * std::sin (segnext); + + // Now draw a quad + sm::vec c4 = { xin, yin, 0.0f }; + sm::vec c3 = { xout, yout, 0.0f }; + sm::vec c2 = { xout_n, yout_n, 0.0f }; + sm::vec c1 = { xin_n, yin_n, 0.0f }; + if ((m_centre > segment && m_centre <= segnext) + || (segment == 0.0f && m_centre == 0.0f) + || (segment == 0.0f && m_centre == sm::mathconst::two_pi)) { + this->computeFlatQuad (tfm * (ro + c1), tfm * (ro + c2), tfm * (ro + c3), tfm * (ro + c4), mc); + } else { + this->computeFlatQuad (tfm * (ro + c1), tfm * (ro + c2), tfm * (ro + c3), tfm * (ro + c4), rc); + } + } + } + + /*! + * Sphere, geodesic polygon version. + * + * This function creates an object with exactly one OpenGL vertex per 'geometric + * vertex of the polyhedron'. That means that colouring this object must be + * achieved by colouring the vertices and faces cannot be coloured + * distinctly. Pass in a single colour for the initial object. To recolour, + * modify the content of vertexColors. + * + * \tparam F The type used for the polyhedron computation. Use float or double. + * + * \param so The sphere offset. Where to place this sphere... + * \param sc The sphere colour. + * \param r Radius of the sphere + * \param iterations how many iterations of the geodesic polygon algo to go + * through. Determines faces: + * + * For 0 iterations, get a geodesic with 20 faces *0 + * For 1 iterations, get a geodesic with 80 faces + * For 2 iterations, get a geodesic with 320 faces *1 + * For 3 iterations, get a geodesic with 1280 faces *2 + * For 4 iterations, get a geodesic with 5120 faces *3 + * For 5 iterations, get a geodesic with 20480 faces *4 + * For 6 iterations, get a geodesic with 81920 faces + * For 7 iterations, get a geodesic with 327680 faces + * For 8 iterations, get a geodesic with 1310720 faces + * For 9 iterations, get a geodesic with 5242880 faces + * + * *0: You'll get an icosahedron + * *1: decent graphical results + * *2: excellent graphical results + * *3: You can *just about* see a difference between 4 iterations and 3, but not + * between 4 and 5. + * *4: The iterations limit if F is float (you'll get a runtime error 'vertices + * has wrong size' for iterations>5) + * + * \return The number of vertices in the generated geodesic sphere + */ + template + std::int32_t computeSphereGeo (sm::vec so, std::array sc, float r = 1.0f, std::int32_t iterations = 2) + { + if (iterations < 0) { throw std::runtime_error ("computeSphereGeo: iterations must be positive"); } + // test if type F is float + if constexpr (std::is_same, float>::value == true) { + if (iterations > 5) { + throw std::runtime_error ("computeSphereGeo: For iterations > 5, F needs to be double precision"); + } + } else { + if (iterations > 10) { + throw std::runtime_error ("computeSphereGeo: This is an abitrary iterations limit (10 gives 20971520 faces)"); + } + } + // Note that we need double precision to compute higher iterations of the geodesic (iterations > 5) + sm::geometry::icosahedral_geodesic geo = sm::geometry::make_icosahedral_geodesic (iterations); + + // Now essentially copy geo into vertex buffers + for (auto v : geo.poly.vertices) { + this->vertex_push (v.as_float() * r + so, this->vertexPositions); + this->vertex_push (v.as_float(), this->vertexNormals); + this->vertex_push_colour (sc, this->vertexColors); + } + for (auto f : geo.poly.faces) { + this->indices.push_back (this->idx + f[0]); + this->indices.push_back (this->idx + f[1]); + this->indices.push_back (this->idx + f[2]); + } + // idx is the *vertex index* and should be incremented by the number of vertices in the polyhedron + std::int32_t n_verts = static_cast(geo.poly.vertices.size()); + this->idx += n_verts; + + return n_verts; + } + + /*! + * Sphere, geodesic polygon version with coloured faces + * + * To colour the faces of this polyhedron, update this->vertexColors (for an + * example see mplot::GeodesicVisual). To make faces distinctly colourizable, we + * have to generate 3 OpenGL vertices for each of the geometric vertices in the + * polyhedron. + * + * \tparam F The type used for the polyhedron computation. Use float or double. + * + * \param so The sphere offset. Where to place this sphere... + * \param sc The default colour + * \param r Radius of the sphere + * \param iterations how many iterations of the geodesic polygon algo to go + * through. Determines number of faces + */ + template + std::int32_t computeSphereGeoFaces (sm::vec so, std::array sc, float r = 1.0f, std::int32_t iterations = 2) + { + if (iterations < 0) { throw std::runtime_error ("computeSphereGeo: iterations must be positive"); } + // test if type F is float + if constexpr (std::is_same, float>::value == true) { + if (iterations > 5) { + throw std::runtime_error ("computeSphereGeo: For iterations > 5, F needs to be double precision"); + } + } else { + if (iterations > 10) { + throw std::runtime_error ("computeSphereGeo: This is an abitrary iterations limit (10 gives 20971520 faces)"); + } + } + // Note that we need double precision to compute higher iterations of the geodesic (iterations > 5) + sm::geometry::icosahedral_geodesic geo = sm::geometry::make_icosahedral_geodesic (iterations); + std::int32_t n_faces = static_cast(geo.poly.faces.size()); + + for (std::int32_t i = 0; i < n_faces; ++i) { // For each face in the geodesic... + sm::vec norm = { F{0}, F{0}, F{0} }; + for (auto vtx : geo.poly.faces[i]) { // For each vertex in face... + norm += geo.poly.vertices[vtx]; // Add to the face norm + this->vertex_push (geo.poly.vertices[vtx].as_float() * r + so, this->vertexPositions); + } + sm::vec nf = (norm / F{3}).as_float(); + for (std::int32_t j = 0; j < 3; ++j) { // Faces all have size 3 + this->vertex_push (nf, this->vertexNormals); + this->vertex_push_colour (sc, this->vertexColors); // A default colour + this->indices.push_back (this->idx + (3 * i) + j); // indices is vertex index + } + } + // An index for each vertex of each face. + this->idx += 3 * n_faces; + + return n_faces; + } + + //! Fast computeSphereGeo, which uses constexpr make_icosahedral_geodesic. The + //! resulting vertices and faces are NOT in any kind of order, but ok for + //! plotting, e.g. scatter graph spheres. + template + std::int32_t computeSphereGeoFast (sm::vec so, std::array sc, float r = 1.0f) + { + // test if type F is float + if constexpr (std::is_same, float>::value == true) { + static_assert (iterations <= 5, "computeSphereGeoFast: For iterations > 5, F needs to be double precision"); + } else { + static_assert (iterations <= 10, "computeSphereGeoFast: This is an abitrary iterations limit (10 gives 20971520 faces)"); + } + // Note that we need double precision to compute higher iterations of the geodesic (iterations > 5) + constexpr sm::geometry_ce::icosahedral_geodesic geo = sm::geometry_ce::make_icosahedral_geodesic(); + + // Now essentially copy geo into vertex buffers + for (auto v : geo.poly.vertices) { + this->vertex_push (v.as_float() * r + so, this->vertexPositions); + this->vertex_push (v.as_float(), this->vertexNormals); + this->vertex_push_colour (sc, this->vertexColors); + } + for (auto f : geo.poly.faces) { + this->indices.push_back (this->idx + f[0]); + this->indices.push_back (this->idx + f[1]); + this->indices.push_back (this->idx + f[2]); + } + // idx is the *vertex index* and should be incremented by the number of vertices in the polyhedron + std::int32_t n_verts = static_cast(geo.poly.vertices.size()); + this->idx += n_verts; + + return n_verts; + } + + /*! + * Sphere, 1 colour version. + * + * Code for creating a sphere as part of this model. I'll use a sphere at the centre of the arrows. + * + * \param so The sphere offset. Where to place this sphere... + * \param sc The sphere colour. + * \param r Radius of the sphere + * \param rings Number of rings used to render the sphere + * \param segments Number of segments used to render the sphere + * + * Number of faces should be (2 + rings) * segments + */ + void computeSphere (sm::vec so, std::array sc, + float r = 1.0f, std::int32_t rings = 10, std::int32_t segments = 12) + { + // First cap, draw as a triangle fan, but record indices so that + // we only need a single call to glDrawElements. + float rings0 = -sm::mathconst::pi_over_2; + float _z0 = std::sin(rings0); + float z0 = r * _z0; + float r0 = std::cos(rings0); + float rings1 = sm::mathconst::pi * (-0.5f + 1.0f / rings); + float _z1 = std::sin(rings1); + float z1 = r * _z1; + float r1 = std::cos(rings1); + // Push the central point + this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); + this->vertex_push (0.0f, 0.0f, -1.0f, this->vertexNormals); + this->vertex_push_colour (sc, this->vertexColors); + + std::uint32_t capMiddle = this->idx++; + std::uint32_t ringStartIdx = this->idx; + std::uint32_t lastRingStartIdx = this->idx; + + bool firstseg = true; + for (std::int32_t j = 0; j < segments; j++) { + float segment = sm::mathconst::two_pi * static_cast(j) / segments; + float x = std::cos(segment); + float y = std::sin(segment); + + float _x1 = x*r1; + float x1 = _x1*r; + float _y1 = y*r1; + float y1 = _y1*r; + + this->vertex_push (so[0]+x1, so[1]+y1, so[2]+z1, this->vertexPositions); + this->vertex_push (_x1, _y1, _z1, this->vertexNormals); + this->vertex_push_colour (sc, this->vertexColors); + + if (!firstseg) { + this->indices.push_back (capMiddle); + this->indices.push_back (this->idx-1); + this->indices.push_back (this->idx++); + } else { + this->idx++; + firstseg = false; + } + } + this->indices.push_back (capMiddle); + this->indices.push_back (this->idx-1); + this->indices.push_back (capMiddle+1); + + // Now add the triangles around the rings + for (std::int32_t i = 2; i < rings; i++) { + + rings0 = sm::mathconst::pi * (-0.5f + static_cast(i) / rings); + _z0 = std::sin(rings0); + z0 = r * _z0; + r0 = std::cos(rings0); + + for (std::int32_t j = 0; j < segments; j++) { + + // "current" segment + float segment = sm::mathconst::two_pi * static_cast(j) / segments; + float x = std::cos(segment); + float y = std::sin(segment); + + // One vertex per segment + float _x0 = x*r0; + float x0 = _x0*r; + float _y0 = y*r0; + float y0 = _y0*r; + + // NB: Only add ONE vertex per segment. ALREADY have the first ring! + this->vertex_push (so[0]+x0, so[1]+y0, so[2]+z0, this->vertexPositions); + // The vertex normal of a vertex that makes up a sphere is + // just a normal vector in the direction of the vertex. + this->vertex_push (_x0, _y0, _z0, this->vertexNormals); + this->vertex_push_colour (sc, this->vertexColors); + + if (j == segments - 1) { + // Last vertex is back to the start + this->indices.push_back (ringStartIdx++); + this->indices.push_back (this->idx); + this->indices.push_back (lastRingStartIdx); + this->indices.push_back (lastRingStartIdx); + this->indices.push_back (this->idx++); + this->indices.push_back (lastRingStartIdx+segments); + } else { + this->indices.push_back (ringStartIdx++); + this->indices.push_back (this->idx); + this->indices.push_back (ringStartIdx); + this->indices.push_back (ringStartIdx); + this->indices.push_back (this->idx++); + this->indices.push_back (this->idx); + } + } + lastRingStartIdx += segments; + } + + // bottom cap + rings0 = sm::mathconst::pi_over_2; + _z0 = std::sin(rings0); + z0 = r * _z0; + r0 = std::cos(rings0); + // Push the central point of the bottom cap + this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); + this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); + this->vertex_push_colour (sc, this->vertexColors); + capMiddle = this->idx++; + firstseg = true; + // No more vertices to push, just do the indices for the bottom cap + ringStartIdx = lastRingStartIdx; + for (std::int32_t j = 0; j < segments; j++) { + if (j != segments - 1) { + this->indices.push_back (capMiddle); + this->indices.push_back (ringStartIdx++); + this->indices.push_back (ringStartIdx); + } else { + // Last segment + this->indices.push_back (capMiddle); + this->indices.push_back (ringStartIdx); + this->indices.push_back (lastRingStartIdx); + } + } + } // end of sphere calculation + + /*! + * Sphere, two colour version. + * + * Code for creating a sphere as part of this model. I'll use a sphere at the + * centre of the arrows. + * + * \param so The sphere offset. Where to place this sphere... + * \param sc The sphere colour. + * \param sc2 The sphere's second colour - used for cap and first ring + * \param r Radius of the sphere + * \param rings Number of rings used to render the sphere + * \param segments Number of segments used to render the sphere + */ + void computeSphere (sm::vec so, std::array sc, std::array sc2, + float r = 1.0f, std::int32_t rings = 10, std::int32_t segments = 12) + { + // First cap, draw as a triangle fan, but record indices so that + // we only need a single call to glDrawElements. + float rings0 = -sm::mathconst::pi_over_2; + float _z0 = std::sin(rings0); + float z0 = r * _z0; + float r0 = std::cos(rings0); + float rings1 = sm::mathconst::pi * (-0.5f + 1.0f / rings); + float _z1 = std::sin(rings1); + float z1 = r * _z1; + float r1 = std::cos(rings1); + // Push the central point + this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); + this->vertex_push (0.0f, 0.0f, -1.0f, this->vertexNormals); + this->vertex_push_colour (sc2, this->vertexColors); + + std::uint32_t capMiddle = this->idx++; + std::uint32_t ringStartIdx = this->idx; + std::uint32_t lastRingStartIdx = this->idx; + + bool firstseg = true; + for (std::int32_t j = 0; j < segments; j++) { + float segment = sm::mathconst::two_pi * static_cast(j) / segments; + float x = std::cos(segment); + float y = std::sin(segment); + + float _x1 = x*r1; + float x1 = _x1*r; + float _y1 = y*r1; + float y1 = _y1*r; + + this->vertex_push (so[0]+x1, so[1]+y1, so[2]+z1, this->vertexPositions); + this->vertex_push (_x1, _y1, _z1, this->vertexNormals); + this->vertex_push_colour (sc2, this->vertexColors); + + if (!firstseg) { + this->indices.push_back (capMiddle); + this->indices.push_back (this->idx-1); + this->indices.push_back (this->idx++); + } else { + this->idx++; + firstseg = false; + } + } + this->indices.push_back (capMiddle); + this->indices.push_back (this->idx-1); + this->indices.push_back (capMiddle+1); + + // Now add the triangles around the rings + for (std::int32_t i = 2; i < rings; i++) { + + rings0 = sm::mathconst::pi * (-0.5f + static_cast(i) / rings); + _z0 = std::sin(rings0); + z0 = r * _z0; + r0 = std::cos(rings0); + + for (std::int32_t j = 0; j < segments; j++) { + + // "current" segment + float segment = sm::mathconst::two_pi * static_cast(j) / segments; + float x = std::cos(segment); + float y = std::sin(segment); + + // One vertex per segment + float _x0 = x*r0; + float x0 = _x0*r; + float _y0 = y*r0; + float y0 = _y0*r; + + // NB: Only add ONE vertex per segment. ALREADY have the first ring! + this->vertex_push (so[0]+x0, so[1]+y0, so[2]+z0, this->vertexPositions); + // The vertex normal of a vertex that makes up a sphere is + // just a normal vector in the direction of the vertex. + this->vertex_push (_x0, _y0, _z0, this->vertexNormals); + if (i == 2 || i > (rings-2)) { + this->vertex_push_colour(sc2, this->vertexColors); + } else { + this->vertex_push_colour (sc, this->vertexColors); + } + if (j == segments - 1) { + // Last vertex is back to the start + this->indices.push_back (ringStartIdx++); + this->indices.push_back (this->idx); + this->indices.push_back (lastRingStartIdx); + this->indices.push_back (lastRingStartIdx); + this->indices.push_back (this->idx++); + this->indices.push_back (lastRingStartIdx+segments); + } else { + this->indices.push_back (ringStartIdx++); + this->indices.push_back (this->idx); + this->indices.push_back (ringStartIdx); + this->indices.push_back (ringStartIdx); + this->indices.push_back (this->idx++); + this->indices.push_back (this->idx); + } + } + lastRingStartIdx += segments; + } + + // bottom cap + rings0 = sm::mathconst::pi_over_2; + _z0 = std::sin(rings0); + z0 = r * _z0; + r0 = std::cos(rings0); + // Push the central point of the bottom cap + this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); + this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); + this->vertex_push_colour (sc2, this->vertexColors); + capMiddle = this->idx++; + firstseg = true; + // No more vertices to push, just do the indices for the bottom cap + ringStartIdx = lastRingStartIdx; + for (std::int32_t j = 0; j < segments; j++) { + if (j != segments - 1) { + this->indices.push_back (capMiddle); + this->indices.push_back (ringStartIdx++); + this->indices.push_back (ringStartIdx); + } else { + // Last segment + this->indices.push_back (capMiddle); + this->indices.push_back (ringStartIdx); + this->indices.push_back (lastRingStartIdx); + } + } + } + + /*! + * Compute an ellipsoid surface of the form x*x/a*a + y*y/b*b + z*z/c*c = 1 + * + * so is the offset position for the ellipsoid + * + * sc is the colour at one end of the z axis + * + * sc2 is the colour at the other end + * + * abc are the three ellipsoid parameters + * + * rings is the number of rings along the z axis + * + * segments is the number of segments in each ring along the z axis + * + * tr transform matrix to apply to each point in the ellipse (applied before so is applied + * as a transform) + */ + void computeEllipsoid (sm::vec so, + std::array sc, + std::array sc2, + sm::vec abc, + std::int32_t rings = 10, std::int32_t segments = 12, + sm::mat tr = sm::mat::identity()) + { + // We have two angular parameters t and t2. t in range 0-2pi and t2 in range 0-pi. t + // gives the 'xy' ellipse; t2 gives the change in size of the xy ellipse as the z axis + // is traversed. + float t = 0.0f; + float t2 = 0.0f; + // used computing normals + sm::vec two_over_abcsq = 2.0f / abc.sq(); + // Holding the coordinates of each point on the ellipsoid as we compute it + sm::vec p = {}; + // The normal vector + sm::vec n = {}; + + // sm::vec versions of the colours + sm::vec _sc = {}; + _sc.set_from (sc); + sm::vec _sc2 = {}; + _sc2.set_from (sc2); + + // Push the central point + p = { 0, 0, abc[2] }; + this->vertex_push (so + (tr * p).less_one_dim(), this->vertexPositions); + n = { 0, 0, 1 }; + this->vertex_push (n, this->vertexNormals); + this->vertex_push_colour (_sc, this->vertexColors); + + std::uint32_t capMiddle = this->idx++; + std::uint32_t ringStartIdx = this->idx; + std::uint32_t lastRingStartIdx = this->idx; + + t2 = sm::mathconst::pi / rings; + p[2] = abc[2] * std::cos(t2); + + bool firstseg = true; + for (std::int32_t j = 0; j < segments; j++) { + + t = sm::mathconst::two_pi * static_cast(j) / segments; + p[0] = abc[0] * std::cos(t) * std::sin(t2); + p[1] = abc[1] * std::sin(t) * std::sin(t2); + + sm::vec<> pp = (tr * p).less_one_dim(); + this->vertex_push (so + pp, this->vertexPositions); + + n = (tr * (p * two_over_abcsq)).less_one_dim(); + n.renormalize(); + this->vertex_push (n, this->vertexNormals); + + sm::vec sc_ring = _sc * (1.0f - 1.0f / rings) + _sc2 * 1.0f / rings; + this->vertex_push_colour (sc_ring, this->vertexColors); + + if (!firstseg) { + this->indices.push_back (capMiddle); + this->indices.push_back (this->idx-1); + this->indices.push_back (this->idx++); + } else { + this->idx++; + firstseg = false; + } + } + this->indices.push_back (capMiddle); + this->indices.push_back (this->idx-1); + this->indices.push_back (capMiddle+1); + + // Now add the triangles around the rings + for (std::int32_t i = 2; i < rings; i++) { + + t2 = sm::mathconst::pi * (static_cast(i) / rings); + p[2] = abc[2] * std::cos(t2); + + sm::vec sc_ring = _sc * (1.0f - static_cast(i) / rings) + _sc2 * static_cast(i) / rings; + + for (std::int32_t j = 0; j < segments; j++) { + + // "current" segment + t = sm::mathconst::two_pi * static_cast(j) / segments; + p[0] = abc[0] * std::cos(t) * std::sin(t2); + p[1] = abc[1] * std::sin(t) * std::sin(t2); + + // NB: Only add ONE vertex per segment. ALREADY have the first ring! + sm::vec<> pp = (tr * p).less_one_dim(); + this->vertex_push (so + pp, this->vertexPositions); + // The vertex normal of a vertex that makes up a sphere is + // just a normal vector in the direction of the vertex. + n = (tr * (p * two_over_abcsq)).less_one_dim(); + n.renormalize(); + this->vertex_push (n, this->vertexNormals); + + this->vertex_push_colour (sc_ring, this->vertexColors); + + if (j == segments - 1) { + // Last vertex is back to the start + this->indices.push_back (ringStartIdx++); + this->indices.push_back (this->idx); + this->indices.push_back (lastRingStartIdx); + this->indices.push_back (lastRingStartIdx); + this->indices.push_back (this->idx++); + this->indices.push_back (lastRingStartIdx+segments); + } else { + this->indices.push_back (ringStartIdx++); + this->indices.push_back (this->idx); + this->indices.push_back (ringStartIdx); + this->indices.push_back (ringStartIdx); + this->indices.push_back (this->idx++); + this->indices.push_back (this->idx); + } + } + lastRingStartIdx += segments; + } + + // bottom cap + + // Push the central point of the bottom cap + p = { 0, 0, -abc[2] }; + this->vertex_push (so + (tr * p).less_one_dim(), this->vertexPositions); + n = { 0, 0, -1 }; + this->vertex_push (n, this->vertexNormals); + this->vertex_push_colour (_sc2, this->vertexColors); + capMiddle = this->idx++; + firstseg = true; + // No more vertices to push, just do the indices for the bottom cap + ringStartIdx = lastRingStartIdx; + for (std::int32_t j = 0; j < segments; j++) { + if (j != segments - 1) { + this->indices.push_back (capMiddle); + this->indices.push_back (ringStartIdx++); + this->indices.push_back (ringStartIdx); + } else { + // Last segment + this->indices.push_back (capMiddle); + this->indices.push_back (ringStartIdx); + this->indices.push_back (lastRingStartIdx); + } + } + } + + /*! + * Compute vertices for an icosahedron. + */ + void computeIcosahedron (sm::vec centre, + std::array, 20> face_colours, + float r = 1.0f) // radius or side length? + { + sm::geometry::polyhedron ico = sm::geometry::icosahedron(); + + for (std::int32_t j = 0; j < 20; ++j) { + // Compute the face normal + sm::vec norml = (ico.vertices[ico.faces[j][0]] + ico.vertices[ico.faces[j][1]] + ico.vertices[ico.faces[j][2]])/3.0f; + this->vertex_push (centre + (ico.vertices[ico.faces[j][0]] * r), this->vertexPositions); + this->vertex_push (centre + (ico.vertices[ico.faces[j][1]] * r), this->vertexPositions); + this->vertex_push (centre + (ico.vertices[ico.faces[j][2]] * r), this->vertexPositions); + for (std::int32_t i = 0; i < 3; ++i) { + this->vertex_push (norml, this->vertexNormals); + this->vertex_push_colour (face_colours[j], this->vertexColors); + } + // Indices... + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+1); + this->indices.push_back (this->idx+2); + this->idx += 3; + } + } + + /*! + * Create a cone. + * + * \param centre The centre of the cone - would be the end of the line + * + * \param tip The tip of the cone + * + * \param ringoffset Move the ring forwards or backwards along the vector from + * \a centre to \a tip. This is positive or negative proportion of tip - centre. + * + * \param col The cone colour + * + * \param r Radius of the ring + * + * \param segments Number of segments used to render the tube + */ + void computeCone (sm::vec centre, + sm::vec tip, + float ringoffset, + std::array col, + float r = 1.0f, std::int32_t segments = 12) + { + // Cone is drawn as a base ring around a centre-of-the-base vertex, an + // intermediate ring which is on the base ring, but has different normals, a + // 'ring' around the tip (with suitable normals) and a 'tip' vertex + + sm::vec vbase = centre; + sm::vec vtip = tip; + sm::vec v = vtip - vbase; + v.renormalize(); + + // circle in a plane defined by a point and a normal + sm::vec rand_vec; + rand_vec.randomize(); + sm::vec inplane = rand_vec.cross(v); + inplane.renormalize(); + sm::vec v_x_inplane = v.cross(inplane); + + // Push the central point of the start cap - this is at location vstart + this->vertex_push (vbase, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + // Base ring with normals in direction -v + for (std::int32_t j = 0; j < segments; j++) { + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; + // Subtract the vector which makes this circle + c = c + (v * ringoffset); + this->vertex_push (vbase+c, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + } + + // Intermediate ring of vertices around/aligned with the base ring with normals in direction c + for (std::int32_t j = 0; j < segments; j++) { + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; + c = c + (v * ringoffset); + this->vertex_push (vbase+c, this->vertexPositions); + c.renormalize(); + this->vertex_push (c, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + } + + // Intermediate ring of vertices around the tip with normals direction c + for (std::int32_t j = 0; j < segments; j++) { + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; + c = c + (v * ringoffset); + this->vertex_push (vtip, this->vertexPositions); + c.renormalize(); + this->vertex_push (c, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + } + + // Push tip vertex as the last vertex, normal is in direction v + this->vertex_push (vtip, this->vertexPositions); + this->vertex_push (v, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + // Number of vertices = segments * 3 + 2. + std::int32_t nverts = segments * 3 + 2; + + // After creating vertices, push all the indices. + std::uint32_t capMiddle = this->idx; + std::uint32_t capStartIdx = this->idx + 1; + std::uint32_t endMiddle = this->idx + static_cast(nverts) - 1u; + std::uint32_t endStartIdx = capStartIdx; + + // Base of the cone + for (std::int32_t j = 0; j < segments-1; j++) { + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + j); + this->indices.push_back (capStartIdx + 1 + j); + } + // Last tri of base + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + segments - 1); + this->indices.push_back (capStartIdx); + + // Middle sections + for (std::int32_t lsection = 0; lsection < 2; ++lsection) { + capStartIdx = this->idx + 1 + lsection*segments; + endStartIdx = capStartIdx + segments; + for (std::int32_t j = 0; j < segments; j++) { + // Triangle 1: + this->indices.push_back (capStartIdx + j); + if (j == (segments-1)) { + this->indices.push_back (capStartIdx); + } else { + this->indices.push_back (capStartIdx + 1 + j); + } + this->indices.push_back (endStartIdx + j); + // Triangle 2: + this->indices.push_back (endStartIdx + j); + if (j == (segments-1)) { + this->indices.push_back (endStartIdx); + } else { + this->indices.push_back (endStartIdx + 1 + j); + } + if (j == (segments-1)) { + this->indices.push_back (capStartIdx); + } else { + this->indices.push_back (capStartIdx + j + 1); + } + } + } + + // tip + for (std::int32_t j = 0; j < segments-1; j++) { + this->indices.push_back (endMiddle); + this->indices.push_back (endStartIdx + j); + this->indices.push_back (endStartIdx + 1 + j); + } + // Last triangle of tip + this->indices.push_back (endMiddle); + this->indices.push_back (endStartIdx + segments - 1); + this->indices.push_back (endStartIdx); + + // Update idx + this->idx += nverts; + } // end of cone calculation + + //! Compute a line with a single colour + void computeLine (sm::vec start, sm::vec end, + sm::vec _uz, + std::array col, + float w = 0.1f, float thickness = 0.01f, float shorten = 0.0f) + { + this->computeLine (start, end, _uz, col, col, w, thickness, shorten); + } + + /*! + * Create a line from \a start to \a end, with width \a w and a colour which + * transitions from the colour \a colStart to \a colEnd. The thickness of the + * line in the z direction is \a thickness + * + * \param start The start of the tube + * \param end The end of the tube + * \param _uz Dirn of z (up) axis for end face of line. Should be normalized. + * \param colStart The tube staring colour + * \param colEnd The tube's ending colour + * \param w width of line + * \param thickness The thickness/depth of the line in uy direction + * \param shorten An amount by which to shorten the length of the line at each end. + */ + void computeLine (sm::vec start, sm::vec end, + sm::vec _uz, + std::array colStart, std::array colEnd, + float w = 0.1f, float thickness = 0.01f, float shorten = 0.0f) + { + // There are always 8 segments for this line object, 2 at each of 4 corners + const std::int32_t segments = 8; + + // The vector from start to end defines direction of the tube + sm::vec vstart = start; + sm::vec vend = end; + sm::vec v = vend - vstart; + v.renormalize(); + + // If shorten is not 0, then modify vstart and vend + if (shorten > 0.0f) { + vstart = start + v * shorten; + vend = end - v * shorten; + } + + // vv is normal to v and _uz + sm::vec vv = v.cross(_uz); + vv.renormalize(); + + // Push the central point of the start cap - this is at location vstart + this->vertex_push (vstart, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (colStart, this->vertexColors); + + // Compute the 'face angles' that will give the correct width and thickness for the line + std::array angles; + float w_ = w * 0.5f; + float d_ = thickness * 0.5f; + float r = std::sqrt (w_ * w_ + d_ * d_); + angles[0] = std::acos (w_ / r); + angles[1] = angles[0]; + angles[2] = sm::mathconst::pi - angles[0]; + angles[3] = angles[2]; + angles[4] = sm::mathconst::pi + angles[0]; + angles[5] = angles[4]; + angles[6] = sm::mathconst::two_pi - angles[0]; + angles[7] = angles[6]; + // The normals for the vertices around the line + std::array, 8> norms = { vv, _uz, _uz, -vv, -vv, -_uz, -_uz, vv }; + + // Start cap vertices (a triangle fan) + for (std::int32_t j = 0; j < segments; j++) { + sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; + this->vertex_push (vstart+c, this->vertexPositions); + this->vertex_push (-v, this->vertexNormals); + this->vertex_push_colour (colStart, this->vertexColors); + } + + // Intermediate, near start cap. Normals point outwards. Need Additional vertices + for (std::int32_t j = 0; j < segments; j++) { + sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; + this->vertex_push (vstart+c, this->vertexPositions); + this->vertex_push (norms[j], this->vertexNormals); + this->vertex_push_colour (colStart, this->vertexColors); + } + + // Intermediate, near end cap. Normals point in direction c + for (std::int32_t j = 0; j < segments; j++) { + sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; + this->vertex_push (vend+c, this->vertexPositions); + this->vertex_push (norms[j], this->vertexNormals); + this->vertex_push_colour (colEnd, this->vertexColors); + } + + // Bottom cap vertices + for (std::int32_t j = 0; j < segments; j++) { + sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; + this->vertex_push (vend+c, this->vertexPositions); + this->vertex_push (v, this->vertexNormals); + this->vertex_push_colour (colEnd, this->vertexColors); + } + + // Bottom cap. Push centre vertex as the last vertex. + this->vertex_push (vend, this->vertexPositions); + this->vertex_push (v, this->vertexNormals); + this->vertex_push_colour (colEnd, this->vertexColors); + + // Number of vertices = segments * 4 + 2. + std::int32_t nverts = (segments * 4) + 2; + + // After creating vertices, push all the indices. + std::uint32_t capMiddle = this->idx; + std::uint32_t capStartIdx = this->idx + 1u; + std::uint32_t endMiddle = this->idx + static_cast(nverts) - 1u; + std::uint32_t endStartIdx = capStartIdx + (3u * segments); + + // Start cap indices + for (std::int32_t j = 0; j < segments-1; j++) { + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + j); + this->indices.push_back (capStartIdx + 1 + j); + } + // Last one + this->indices.push_back (capMiddle); + this->indices.push_back (capStartIdx + segments - 1); + this->indices.push_back (capStartIdx); + + // Middle sections + for (std::int32_t lsection = 0; lsection < 3; ++lsection) { + capStartIdx = this->idx + 1 + lsection*segments; + endStartIdx = capStartIdx + segments; + for (std::int32_t j = 0; j < segments; j++) { + this->indices.push_back (capStartIdx + j); + if (j == (segments-1)) { + this->indices.push_back (capStartIdx); + } else { + this->indices.push_back (capStartIdx + 1 + j); + } + this->indices.push_back (endStartIdx + j); + this->indices.push_back (endStartIdx + j); + if (j == (segments-1)) { + this->indices.push_back (endStartIdx); + } else { + this->indices.push_back (endStartIdx + 1 + j); + } + if (j == (segments-1)) { + this->indices.push_back (capStartIdx); + } else { + this->indices.push_back (capStartIdx + j + 1); + } + } + } + + // bottom cap + for (std::int32_t j = 0; j < segments-1; j++) { + this->indices.push_back (endMiddle); + this->indices.push_back (endStartIdx + j); + this->indices.push_back (endStartIdx + 1 + j); + } + this->indices.push_back (endMiddle); + this->indices.push_back (endStartIdx + segments - 1); + this->indices.push_back (endStartIdx); + + // Update idx + this->idx += nverts; + } // end computeLine + + // Like computeLine, but this line has no thickness. + void computeFlatLine (sm::vec start, sm::vec end, + sm::vec _uz, + std::array col, + float w = 0.1f, float shorten = 0.0f) + { + // The vector from start to end defines direction of the tube + sm::vec vstart = start; + sm::vec vend = end; + sm::vec v = vend - vstart; + v.renormalize(); + + // If shorten is not 0, then modify vstart and vend + if (shorten > 0.0f) { + vstart = start + v * shorten; + vend = end - v * shorten; + } + + // vv is normal to v and _uz + sm::vec vv = v.cross(_uz); + vv.renormalize(); + + // corners of the line, and the start angle is determined from vv and w + sm::vec ww = vv * w * 0.5f; + sm::vec c1 = vstart + ww; + sm::vec c2 = vstart - ww; + sm::vec c3 = vend - ww; + sm::vec c4 = vend + ww; + + this->vertex_push (c1, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c2, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c3, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c4, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + // Number of vertices = segments * 4 + 2. + std::int32_t nverts = 4; + + // After creating vertices, push all the indices. + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+1); + this->indices.push_back (this->idx+2); + + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+2); + this->indices.push_back (this->idx+3); + + // Update idx + this->idx += nverts; + + } // end computeFlatLine + + // Like computeFlatLine but with option to add rounded start/end caps (I lazily + // draw a whole circle around start/end to achieve this, rather than figuring + // out a semi-circle). + void computeFlatLineRnd (sm::vec start, sm::vec end, + sm::vec _uz, + std::array col, + float w = 0.1f, float shorten = 0.0f, bool startcaps = true, bool endcaps = true) + { + // The vector from start to end defines direction of the tube + sm::vec vstart = start; + sm::vec vend = end; + sm::vec v = vend - vstart; + v.renormalize(); + + // If shorten is not 0, then modify vstart and vend + if (shorten > 0.0f) { + vstart = start + v * shorten; + vend = end - v * shorten; + } + + // vv is normal to v and _uz + sm::vec vv = v.cross(_uz); + vv.renormalize(); + + // corners of the line, and the start angle is determined from vv and w + sm::vec ww = vv * w * 0.5f; + sm::vec c1 = vstart + ww; + sm::vec c2 = vstart - ww; + sm::vec c3 = vend - ww; + sm::vec c4 = vend + ww; + + std::int32_t segments = 12; + float r = 0.5f * w; + std::uint32_t startvertices = 0u; + if (startcaps) { + // Push the central point of the start cap - this is at location vstart + this->vertex_push (vstart, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + ++startvertices; + // Start cap vertices (a triangle fan) + for (std::int32_t j = 0; j < segments; j++) { + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = { std::sin(t) * r, std::cos(t) * r, 0.0f }; + this->vertex_push (vstart+c, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + ++startvertices; + } + } + + this->vertex_push (c1, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c2, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c3, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c4, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + std::uint32_t endvertices = 0u; + if (endcaps) { + // Push the central point of the end cap - this is at location vend + this->vertex_push (vend, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + ++endvertices; + // End cap vertices (a triangle fan) + for (std::int32_t j = 0; j < segments; j++) { + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c = { std::sin(t) * r, std::cos(t) * r, 0.0f }; + this->vertex_push (vend+c, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + ++endvertices; + } + } + + // After creating vertices, push all the indices. + + if (startcaps) { // prolly startcaps, for flexibility + std::uint32_t topcap = this->idx; + for (std::int32_t j = 0; j < segments; j++) { + std::int32_t inc1 = 1+j; + std::int32_t inc2 = 1+((j+1)%segments); + this->indices.push_back (topcap); + this->indices.push_back (topcap+inc1); + this->indices.push_back (topcap+inc2); + } + this->idx += startvertices; + } + + // The line itself + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+1); + this->indices.push_back (this->idx+2); + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+2); + this->indices.push_back (this->idx+3); + // Update idx + this->idx += 4; + + if (endcaps) { + std::uint32_t botcap = this->idx; + for (std::int32_t j = 0; j < segments; j++) { + std::int32_t inc1 = 1+j; + std::int32_t inc2 = 1+((j+1)%segments); + this->indices.push_back (botcap); + this->indices.push_back (botcap+inc1); + this->indices.push_back (botcap+inc2); + } + this->idx += endvertices; + } + } // end computeFlatLine + + /*! + * Like computeFlatLine, but this line has no thickness and you can provide the + * previous and next data points so that this line, the previous line and the + * next line can line up perfectly without drawing a circular rounded 'end cap'! + * + * This code assumes that the coordinates prev, start, end, next all lie on a 2D + * plane normal to _uz. In fact, the 3D coordinates start, end, prev and next + * will all be projected onto the plane defined by _uz, so that they can be + * reduced to 2D coordinates. This then allows crossing points of lines to be + * computed. + * + * If you want to make a ribbon between points that do *not* lie on a 2D plane, + * you'll need to write another graphics primitive function. + */ + void computeFlatLine (sm::vec start, sm::vec end, + sm::vec prev, sm::vec next, + sm::vec _uz, + std::array col, + float w = 0.1f) + { + // Corner coordinates for this line section + sm::vec c1 = { 0.0f }; + sm::vec c2 = { 0.0f }; + sm::vec c3 = { 0.0f }; + sm::vec c4 = { 0.0f }; + + // Ensure _uz is a unit vector + sm::vec __uz = _uz; + __uz.renormalize(); + + // First find the rotation to make __uz into the actual unit z dirn + sm::quaternion rotn; + sm::vec basis_rotn_axis = __uz.cross (sm::vec<>::uz()); + if (basis_rotn_axis.length() > 0.0f) { + float basis_rotn_angle = __uz.angle (sm::vec<>::uz(), basis_rotn_axis); + rotn.rotate (basis_rotn_axis, basis_rotn_angle); + } // else nothing to do - basis rotn is null + + // Transform so that start is the origin + // sm::vec s_o = { 0.0f }; // by defn + sm::vec e_o = end - start; + sm::vec p_o = prev - start; + sm::vec n_o = next - start; + + // Apply basis rotation just to the end point. e_b: 'end point in rotated basis' + sm::vec e_b = rotn * e_o; + + // Use the vector from start to end as the in-plane x dirn. Do this AFTER + // first coord rotn. In other words: find the rotation about the new unit z + // direction to force the end point to be on the x axis + sm::vec plane_x = e_b; // - s_b but s_b is (0,0,0) by defn + plane_x.renormalize(); + sm::vec plane_y = sm::vec<>::uz().cross (plane_x); + plane_y.renormalize(); + // Find the in-plane coordinates in the rotated plane system + sm::vec e_p = { plane_x.dot (e_b), plane_y.dot (e_b), sm::vec<>::uz().dot (e_b) }; + + // One epsilon is exacting + if (std::abs(e_p[2]) > std::numeric_limits::epsilon()) { + throw std::runtime_error ("uz not orthogonal to the line start -> end?"); + } + + // From e_p and e_b (which should both be in a 2D plane) figure out what + // angle of rotation brings e_b into the x axis + float inplane_rotn_angle = e_b.angle (e_p, sm::vec<>::uz()); + sm::quaternion inplane_rotn (sm::vec<>::uz(), inplane_rotn_angle); + + // Apply the in-plane rotation to the basis rotation + rotn.premultiply (inplane_rotn); + + // Transform points + sm::vec p_p = rotn * p_o; + sm::vec n_p = rotn * n_o; + //vec s_p = rotn * s_o; // not necessary, s_p = (0,0,0) by defn + + // Line crossings time. + sm::vec c1_p = { 0.0f }; // 2D crossing coords that we're going to find + sm::vec c2_p = { 0.0f }; + sm::vec c3_p = e_p.less_one_dim(); + sm::vec c4_p = e_p.less_one_dim(); + + // 3 lines on each side. l_p, l_c (current) and l_n. Each has two ends. l_p_1, l_p_2 etc. + + // 'prev' 'cur' and 'next' vectors + sm::vec p_vec = (/*s_p*/ -p_p).less_one_dim(); + sm::vec c_vec = e_p.less_one_dim(); + sm::vec n_vec = (n_p - e_p).less_one_dim(); + + sm::vec p_ortho = (/*s_p*/ - p_p).cross (sm::vec<>::uz()).less_one_dim(); + p_ortho.renormalize(); + sm::vec c_ortho = (e_p /*- s_p*/).cross (sm::vec<>::uz()).less_one_dim(); + c_ortho.renormalize(); + sm::vec n_ortho = (n_p - e_p).cross (sm::vec<>::uz()).less_one_dim(); + n_ortho.renormalize(); + + const float hw = w / 2.0f; + + sm::vec l_p_1 = p_p.less_one_dim() + (p_ortho * hw) - p_vec; // makes it 3 times as long as the line. + sm::vec l_p_2 = /*s_p.less_one_dim() +*/ (p_ortho * hw) + p_vec; + sm::vec l_c_1 = /*s_p.less_one_dim() +*/ (c_ortho * hw) - c_vec; + sm::vec l_c_2 = e_p.less_one_dim() + (c_ortho * hw) + c_vec; + sm::vec l_n_1 = e_p.less_one_dim() + (n_ortho * hw) - n_vec; + sm::vec l_n_2 = n_p.less_one_dim() + (n_ortho * hw) + n_vec; + + std::bitset<2> isect = sm::geometry::segments_intersect (l_p_1, l_p_2, l_c_1, l_c_2); + if (isect.test(0) == true && isect.test(1) == false) { // test for intersection but not colinear + c1_p = sm::geometry::crossing_point (l_p_1, l_p_2, l_c_1, l_c_2); + } else if (isect.test(0) == true && isect.test(1) == true) { + c1_p = /*s_p.less_one_dim() +*/ (c_ortho * hw); + } else { // no intersection. prev could have been start + c1_p = /*s_p.less_one_dim() +*/ (c_ortho * hw); + } + isect = sm::geometry::segments_intersect (l_c_1, l_c_2, l_n_1, l_n_2); + if (isect.test(0) == true && isect.test(1) == false) { + c4_p = sm::geometry::crossing_point (l_c_1, l_c_2, l_n_1, l_n_2); + } else if (isect.test(0) == true && isect.test(1) == true) { + c4_p = e_p.less_one_dim() + (c_ortho * hw); + } else { // no intersection, prev could have been end + c4_p = e_p.less_one_dim() + (c_ortho * hw); + } + + // o for 'other side'. Could re-use vars in future version. Or just subtract (*_ortho * w) from each. + sm::vec o_l_p_1 = p_p.less_one_dim() - (p_ortho * hw) - p_vec; // makes it 3 times as long as the line. + sm::vec o_l_p_2 = /*s_p.less_one_dim()*/ - (p_ortho * hw) + p_vec; + sm::vec o_l_c_1 = /*s_p.less_one_dim()*/ - (c_ortho * hw) - c_vec; + sm::vec o_l_c_2 = e_p.less_one_dim() - (c_ortho * hw) + c_vec; + sm::vec o_l_n_1 = e_p.less_one_dim() - (n_ortho * hw) - n_vec; + sm::vec o_l_n_2 = n_p.less_one_dim() - (n_ortho * hw) + n_vec; + + isect = sm::geometry::segments_intersect (o_l_p_1, o_l_p_2, o_l_c_1, o_l_c_2); + if (isect.test(0) == true && isect.test(1) == false) { // test for intersection but not colinear + c2_p = sm::geometry::crossing_point (o_l_p_1, o_l_p_2, o_l_c_1, o_l_c_2); + } else if (isect.test(0) == true && isect.test(1) == true) { + c2_p = /*s_p.less_one_dim()*/ - (c_ortho * hw); + } else { // no intersection. prev could have been start + c2_p = /*s_p.less_one_dim()*/ - (c_ortho * hw); + } + + isect = sm::geometry::segments_intersect (o_l_c_1, o_l_c_2, o_l_n_1, o_l_n_2); + if (isect.test(0) == true && isect.test(1) == false) { + c3_p = sm::geometry::crossing_point (o_l_c_1, o_l_c_2, o_l_n_1, o_l_n_2); + } else if (isect.test(0) == true && isect.test(1) == true) { + c3_p = e_p.less_one_dim() - (c_ortho * hw); + } else { // no intersection. next could have been end + c3_p = e_p.less_one_dim() - (c_ortho * hw); + } + + // Transform and rotate back into c1-c4 + sm::quaternion rotn_inv = rotn.invert(); + c1 = rotn_inv * c1_p.plus_one_dim() + start; + c2 = rotn_inv * c2_p.plus_one_dim() + start; + c3 = rotn_inv * c3_p.plus_one_dim() + start; + c4 = rotn_inv * c4_p.plus_one_dim() + start; + + // Now create the vertices from these four corners, c1-c4 + this->vertex_push (c1, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c2, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c3, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c4, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+1); + this->indices.push_back (this->idx+2); + + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+2); + this->indices.push_back (this->idx+3); + + // Update idx + this->idx += 4; + } // end computeFlatLine that joins perfectly + + //! Make a joined up line with previous. + void computeFlatLineP (sm::vec start, sm::vec end, + sm::vec prev, + sm::vec _uz, + std::array col, + float w = 0.1f) + { + this->computeFlatLine (start, end, prev, end, _uz, col, w); + } // end computeFlatLine that joins perfectly with prev + + //! Flat line, joining up with next + void computeFlatLineN (sm::vec start, sm::vec end, + sm::vec next, + sm::vec _uz, + std::array col, + float w = 0.1f) + { + this->computeFlatLine (start, end, start, next, _uz, col, w); + } + + // Like computeLine, but this line has no thickness and it's dashed. + // dashlen: the length of dashes + // gap prop: The proportion of dash length used for the gap + void computeFlatDashedLine (sm::vec start, sm::vec end, + sm::vec _uz, + std::array col, + float w = 0.1f, float shorten = 0.0f, + float dashlen = 0.1f, float gapprop = 0.3f) + { + if (dashlen == 0.0f) { return; } + + // The vector from start to end defines direction of the line + sm::vec vstart = start; + sm::vec vend = end; + + sm::vec v = vend - vstart; + float linelen = v.length(); + v.renormalize(); + + // If shorten is not 0, then modify vstart and vend + if (shorten > 0.0f) { + vstart = start + v * shorten; + vend = end - v * shorten; + linelen = v.length() - shorten * 2.0f; + } + + // vv is normal to v and _uz + sm::vec vv = v.cross(_uz); + vv.renormalize(); + + // Loop, creating the dashes + sm::vec dash_s = vstart; + sm::vec dash_e = dash_s + v * dashlen; + sm::vec dashes = dash_e - vstart; + + while (dashes.length() < linelen) { + + // corners of the line, and the start angle is determined from vv and w + sm::vec ww = vv * w * 0.5f; + sm::vec c1 = dash_s + ww; + sm::vec c2 = dash_s - ww; + sm::vec c3 = dash_e - ww; + sm::vec c4 = dash_e + ww; + + this->vertex_push (c1, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c2, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c3, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + this->vertex_push (c4, this->vertexPositions); + this->vertex_push (_uz, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + + // Number of vertices = segments * 4 + 2. + std::int32_t nverts = 4; + + // After creating vertices, push all the indices. + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+1); + this->indices.push_back (this->idx+2); + + this->indices.push_back (this->idx); + this->indices.push_back (this->idx+2); + this->indices.push_back (this->idx+3); + + // Update idx + this->idx += nverts; + + // Next dash + dash_s = dash_e + v * dashlen * gapprop; + dash_e = dash_s + v * dashlen; + dashes = dash_e - vstart; + } + + } // end computeFlatDashedLine + + // Compute a flat line circle outline + void computeFlatCircleLine (sm::vec centre, sm::vec norm, sm::vec inplane, float radius, + float linewidth, std::array col, std::int32_t segments = 128) + { + inplane.renormalize(); + sm::vec norm_x_inplane = norm.cross(inplane); + + float half_lw = linewidth / 2.0f; + float r_in = radius - half_lw; + float r_out = radius + half_lw; + // Inner ring at radius radius-linewidth/2 with normals in direction norm; + // Outer ring at radius radius+linewidth/2 with normals also in direction norm + for (std::int32_t j = 0; j < segments; j++) { + float t = j * sm::mathconst::two_pi / static_cast(segments); + sm::vec c_in = inplane * std::sin(t) * r_in + norm_x_inplane * std::cos(t) * r_in; + this->vertex_push (centre+c_in, this->vertexPositions); + this->vertex_push (norm, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + sm::vec c_out = inplane * std::sin(t) * r_out + norm_x_inplane * std::cos(t) * r_out; + this->vertex_push (centre+c_out, this->vertexPositions); + this->vertex_push (norm, this->vertexNormals); + this->vertex_push_colour (col, this->vertexColors); + } + // Added 2*segments vertices to vertexPositions + + // After creating vertices, push all the indices. + for (std::int32_t j = 0; j < segments; j++) { + std::int32_t jn = (segments + ((j+1) % segments)) % segments; + this->indices.push_back (this->idx+(2*j)); + this->indices.push_back (this->idx+(2*jn)); + this->indices.push_back (this->idx+(2*jn+1)); + this->indices.push_back (this->idx+(2*j)); + this->indices.push_back (this->idx+(2*jn+1)); + this->indices.push_back (this->idx+(2*j+1)); + } + this->idx += 2 * segments; // nverts + + } // end computeFlatCircleLine + + // Compute a flat line circle outline + void computeFlatCircleLine (sm::vec centre, sm::vec norm, float radius, + float linewidth, std::array col, std::int32_t segments = 128) + { + // circle in a plane defined by a point (v0 = vstart or vend) and a normal + // (v) can be found: Choose random vector vr. A vector inplane = vr ^ v. The + // unit in-plane vector is inplane.normalise. Can now use that vector in the + // plan to define a point on the circle. Note that this starting point on + // the circle is at a random position, which means that this version of + // computeFlatCircleLine is useful for tubes that have quite a few segments. + sm::vec rand_vec; + rand_vec.randomize(); + sm::vec inplane = rand_vec.cross(norm); + // Sub call to the method that takes a normal vector AND an inplane vector: + this->computeFlatCircleLine (centre, norm, inplane, radius, linewidth, col, segments); + } + + // Compute triangles to form a true cuboid from 8 corners. + void computeCuboid (const std::array, 8>& v, const std::array& clr) + { + this->computeFlatQuad (v[0], v[1], v[2], v[3], clr); + this->computeFlatQuad (v[0], v[4], v[5], v[1], clr); + this->computeFlatQuad (v[1], v[5], v[6], v[2], clr); + this->computeFlatQuad (v[2], v[6], v[7], v[3], clr); + this->computeFlatQuad (v[3], v[7], v[4], v[0], clr); + this->computeFlatQuad (v[7], v[6], v[5], v[4], clr); + } + + // Compute a rhombus using the four defining coordinates. The coordinates are named as if + // they were the origin, x, y and z of a right-handed 3D coordinate system. These define three edges + void computeRhombus (const sm::vec& o, const sm::vec& x, const sm::vec& y, const sm::vec& z, + const std::array& clr) + { + // Edge vectors + sm::vec edge1 = x - o; + sm::vec edge2 = y - o; + sm::vec edge3 = z - o; + + // Compute the face normals + sm::vec _n1 = edge1.cross (edge2); + _n1.renormalize(); + sm::vec _n2 = edge2.cross (edge3); + _n2.renormalize(); + sm::vec _n3 = edge1.cross (edge3); + _n3.renormalize(); + + // Push positions and normals for 24 vertices to make up the rhombohedron; 4 for each face. + // Front face + this->vertex_push (o, this->vertexPositions); + this->vertex_push (o + edge1, this->vertexPositions); + this->vertex_push (o + edge3, this->vertexPositions); + this->vertex_push (o + edge1 + edge3, this->vertexPositions); + for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (_n3, this->vertexNormals); } + // Top face + this->vertex_push (o + edge3, this->vertexPositions); + this->vertex_push (o + edge1 + edge3, this->vertexPositions); + this->vertex_push (o + edge2 + edge3, this->vertexPositions); + this->vertex_push (o + edge2 + edge1 + edge3, this->vertexPositions); + for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (_n1, this->vertexNormals); } + // Back face + this->vertex_push (o + edge2 + edge3, this->vertexPositions); + this->vertex_push (o + edge2 + edge1 + edge3, this->vertexPositions); + this->vertex_push (o + edge2, this->vertexPositions); + this->vertex_push (o + edge2 + edge1, this->vertexPositions); + for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (-_n3, this->vertexNormals); } + // Bottom face + this->vertex_push (o + edge2, this->vertexPositions); + this->vertex_push (o + edge2 + edge1, this->vertexPositions); + this->vertex_push (o, this->vertexPositions); + this->vertex_push (o + edge1, this->vertexPositions); + for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (-_n1, this->vertexNormals); } + // Left face + this->vertex_push (o + edge2, this->vertexPositions); + this->vertex_push (o, this->vertexPositions); + this->vertex_push (o + edge2 + edge3, this->vertexPositions); + this->vertex_push (o + edge3, this->vertexPositions); + for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (-_n2, this->vertexNormals); } + // Right face + this->vertex_push (o + edge1, this->vertexPositions); + this->vertex_push (o + edge1 + edge2, this->vertexPositions); + this->vertex_push (o + edge1 + edge3, this->vertexPositions); + this->vertex_push (o + edge1 + edge2 + edge3, this->vertexPositions); + for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (_n2, this->vertexNormals); } + + // Vertex colours are all the same + for (std::uint16_t i = 0U; i < 24U; ++i) { this->vertex_push_colour (clr, this->vertexColors); } + + // Indices for 6 faces + for (std::uint16_t i = 0U; i < 6U; ++i) { + this->indices.push_back (this->idx++); + this->indices.push_back (this->idx++); + this->indices.push_back (this->idx--); + this->indices.push_back (this->idx++); + this->indices.push_back (this->idx++); + this->indices.push_back (this->idx++); + } + } // computeCuboid + + // Compute a rectangular cuboid of width (in x), height (in y) and depth (in z). + void computeRectCuboid (const sm::vec& o, const float wx, const float hy, const float dz, + const std::array& clr) + { + sm::vec px = o + sm::vec{wx, 0, 0}; + sm::vec py = o + sm::vec{0, hy, 0}; + sm::vec pz = o + sm::vec{0, 0, dz}; + this->computeRhombus (o, px, py, pz, clr); + } + + // Compute the bounding box frame + void computeBoundingBox() + { + // Draw a frame of tubes from bb.min to bb.max + const float& x0 = this->bb.min[0]; + const float& y0 = this->bb.min[1]; + const float& z0 = this->bb.min[2]; + + const float& x1 = this->bb.max[0]; + const float& y1 = this->bb.max[1]; + const float& z1 = this->bb.max[2]; + + const sm::vec& c0 = this->bb.min; + sm::vec c1 = { x1, y0, z0 }; + sm::vec c2 = { x1, y1, z0 }; + sm::vec c3 = { x0, y1, z0 }; + + sm::vec c4 = { x0, y0, z1 }; + sm::vec c5 = { x1, y0, z1 }; + const sm::vec& c6 = this->bb.max; + sm::vec c7 = { x0, y1, z1 }; + + constexpr std::int32_t segs = 4; + constexpr float zrot = 0.0f; + auto cl = this->colour_bb; + + // Frame tube radius + float r = this->bb.span().length() / 500.0f; + + // Base + this->computeTube (c0, c1, sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + this->computeTube (c1, c2, -sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + this->computeTube (c2, c3, -sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + this->computeTube (c3, c0, sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + // Top + this->computeTube (c4, c5, sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + this->computeTube (c5, c6, -sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + this->computeTube (c6, c7, -sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + this->computeTube (c7, c4, sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); + // Sides + this->computeTube (c0, c4, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); + this->computeTube (c1, c5, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); + this->computeTube (c2, c6, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); + this->computeTube (c3, c7, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); + + // Oriented bounding box local axes/half-extents may be useful when debugging + constexpr bool show_obb_vectors = false; + if constexpr (show_obb_vectors) { + const sm::vec obb_centre = this->bb.mid(); + this->computeTube (obb_centre, obb_centre + this->bb_x, sm::vec::uy(), sm::vec::uz(), + cl, mplot::colour::crimson, r, segs, zrot, true); + this->computeTube (obb_centre, obb_centre + this->bb_y, sm::vec::uz(), sm::vec::ux(), + cl, mplot::colour::springgreen2, r, segs, zrot, true); + this->computeTube (obb_centre, obb_centre + this->bb_z, sm::vec::ux(), sm::vec::uy(), + cl, mplot::colour::blue2, r, segs, zrot, true); + } + } + }; + +} // namespace mplot diff --git a/mplot/VisualOwnable.hpp b/mplot/VisualOwnable.hpp new file mode 100644 index 00000000..02f1fa70 --- /dev/null +++ b/mplot/VisualOwnable.hpp @@ -0,0 +1,2495 @@ +/*! + * \file + * + * Awesome graphics code for high performance graphing and visualisation. + * + * This is intermediate class that sets up (multicontext aware) GL, leaving choice of window system + * (GLFW3/Qt/wx/etc) to a derived class such as mplot::Visual or mplot::qt::viswidget. + * + * This class is 'ownable', and can be used in other window drawing system such as Qt and wx, as + * well as within mplot::Visual, which marries it with the GLFW3 windowing system. + * + * Created by Seb James on 2025/03/01, from mplot::Visual.h + * + * \author Seb James + * \date March 2025 + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // complaint about #include . functional also in VisualModel, VisualResources. +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +import mplot.version; +import mplot.visualmodel; // make header +import mplot.win_t; +import mplot.visualcommon; +import mplot.visualtextmodel; +import mplot.textgeometry; +import mplot.textfeatures; +import mplot.coordarrows; +import mplot.gl.version; +import mplot.gl.util; +import mplot.tools; +import mplot.loadpng; // Use Lode Vandevenne's PNG encoder +import mplot.keys; + +import sm.mathconst; +import sm.vec; +import sm.flags; +import sm.quaternion; +import sm.mat; + +namespace mplot +{ + //! Here are our boolean state flags + enum class visual_state : std::uint32_t + { + readyToFinish, + //! paused can be set true so that pauseOpen() can be used to display the window mid-simulation + paused, + //! If you set this to true, then the mouse movements won't change scenetrans or rotation. + sceneLocked, + //! When true, cursor movements induce rotation of scene + rotateMode, + //! When true, rotations about the third axis are possible. + rotateModMode, + //! When true, cursor movements induce translation of scene + translateMode, + //! We are scrolling (and so we will need to zero scenetrans_delta after enacting the change) + scrolling, + //! True means that at least one of our VisualModels is an instanced rendering model + haveInstanced, + //! Left mouse button is down + mouseButtonLeftPressed, + //! Right mouse button is down + mouseButtonRightPressed, + //! If client code changes viewfollowsVMTranslations or viewFollowsVMBehind, this should be + //! set to signal to computeSceneview that the lastSceneview should be saved or restored to. + viewFollowsModeChanged, + //! Set true while the sceneview is 'zooming back' to the overview mode (or the whereever-you-left-it mode) + viewTransition, + //! Set true if we're in the middle of a scripted sceneview change, such as zooming in over a period of time + viewAutomation + }; + + //! Boolean options - similar to state, but more likely to be modified by client code + enum class visual_options : std::uint32_t + { + //! Set true to disable the 'X' button on the Window from exiting the program + preventWindowCloseWithButton, + //! Set to true to show the coordinate arrows + showCoordArrows, + //! If true, then place the coordinate arrows at the origin of the scene, rather than offset. + coordArrowsInScene, + //! Show user frame of reference (for debug) + showUserFrame, + //! Set to true to show the title text within the scene + showTitle, + //! Set true to output some user information to stdout (e.g. user requested quit) + userInfoStdout, + //! If true, output mplot version to stdout + versionStdout, + //! If true (the default), then call swapBuffers() at the end of render() + renderSwapsBuffers, + /*! + * If true, rotation is about the scene origin, rather than the most central VisualModel. + * + * If false, the system finds the most central VisualModel, and rotates about the centroid + * of the bounding box that surrounds that VisualModel. + */ + rotateAboutSceneOrigin, + /*! + * If true, horizontal mouse movements rotate the scene about a chosen vertical axis, and + * vertical mouse movements rotate the vertical axis about the bottom of the user's + * viewport. This will be familiar to Blender users. Additionally, if the ctrl-modified + * mouse move mode is enabled, the scene is tilted about the axis coming out of the + * viewport. + * + * If false, horizontal mouse movements rotate the scene about the vertical axis of the + * user's viewport, vertcial mouse movements rotate the scene about the horizontal axis of + * the viewport, and ctrl-modified mouse movements rotate the scene about the axis coming + * out of the viewport. This was the original scene navigation scheme in mathplot and before + * that in morphologica. + */ + rotateAboutVertical, + /*! + * If true, write bounding boxes out to a json file /tmp/mathplot_bounding_boxes.json that + * can be read with the show_boundingboxes program + */ + boundingBoxesToJson, + //! If true, draw all the bounding boxes around the VisualModels + showBoundingBoxes, + /*! + * If true, then turn on the bounding box for the VM about which we are rotating and turn + * the others off (ignoring the value of 'showBoundingBoxes') + */ + highlightRotationVM, + /*! + * If true, the view of the scene follows a model translation (one of the VisualModels in + * the scene has to be nominated as the 'model to follow'. Useful for top-down views. The + * selected model to follow is in a member attribute followedModel + */ + viewFollowsVMTranslations, + /*! + * The view 'camera' rotates with the selected VM (followedModel) + */ + viewFollowsVMBehind + }; + + //! Whether to render with perspective or orthographic + enum class perspective_type : std::uint32_t + { + perspective, + orthographic + }; + + //! Automated sceneview transforms, i.e. 'film direction' events. enumerated type of event. + enum class direction_event : std::uint32_t + { + sceneview, + timed_translation, + timed_rotation, + timed_transform, // Move towards a given sceneview + timed_orbit, // Starting from any sceneview, orbit a point + unknown + }; + + //! Automated sceneview transforms, i.e. 'film direction' events. This holds the data for an event. + struct direction_data + { + direction_event event = direction_event::unknown; + // a sceneview to move to, either instantaneously, or over a period of time + sm::mat sceneview = sm::mat::identity(); + sm::vec translation = {}; // A translation to apply to sceneview over time transform_time + sm::vec orbit_centre = {}; // Centre of the orbit for timed_orbit + sm::vec orbit_axis = sm::vec::uz(); + float orbit_angle = sm::mathconst::pi; + sm::quaternion rotation_start;// Holds the rotation of the sceneview at the start of the transform + sm::quaternion rotation; // A rotation of sceneview to achieve over time transform_time. + float about_vert_angle = 0.0f; // A rotation about the scene's up axis (in degrees) + float tilt_angle = 0.0f; + bool min_jerk = true; // Should the movement be minimum jerk, or linear? + std::uint32_t transform_time_frames = 0u; // Specify transform time in frames + std::uint32_t start_frame = std::numeric_limits::max(); + std::uint32_t id = std::numeric_limits::max(); // An ID for this direction (could be tied to movement frame) + }; + + /*! + * VisualOwnable - An ownable 'scene' base class. + * + * This class assumes that GL functions have been loaded by the GLAD header system as a + * GladGLContext pointer, which is called glfn here. GL function calls are glfn->Clear for + * Clear() and glfn->Enable() for Enable() and so on. + * + * \tparam glver The OpenGL version, encoded as a single int (see mplot::gl::version) + */ + template + class VisualOwnable + { + public: + /*! + * Default constructor is used when incorporating Visual inside another object + * such as a QWidget. We have to wait on calling init functions until an OpenGL + * environment is guaranteed to exist. + */ + VisualOwnable() + { + this->sceneview.translate (this->scenetrans_default); + this->sceneview_tr.translate (this->scenetrans_default); + } + + /*! + * Construct a new visualiser. The rule is 1 window to one Visual object. So, this creates a + * new window and a new OpenGL context. + */ + VisualOwnable (const std::int32_t _width, const std::int32_t _height, const std::string& _title, const bool _version_stdout = true) + { + this->sceneview.translate (this->scenetrans_default); + this->sceneview_tr.translate (this->scenetrans_default); + this->window_w = _width; + this->window_h = _height; + this->title = _title; + this->options.set (visual_options::versionStdout, _version_stdout); + this->init_gl(); + } + + ~VisualOwnable() {} + + //! Deconstruct gl memory/context + void deconstructCommon() + { + // Explicitly deconstruct any owned VisualModels + this->vm.clear(); + // Explicitly deconstruct coordArrows, textModel and texts here + this->coordArrows.reset (nullptr); + this->textModel.reset (nullptr); + for (std::uint32_t i = 0; i < this->texts.size(); ++i) { this->texts[i].reset (nullptr); } + //for (auto& t : this->texts) { t.reset (nullptr); } + + if (this->shaders.gprog) { + this->glfn->DeleteProgram (this->shaders.gprog); + this->shaders.gprog = 0; + } + if (this->shaders.tprog) { + this->glfn->DeleteProgram (this->shaders.tprog); + this->shaders.tprog = 0; + } + this->free_gladgl_context (this->glfn); + + // Free up the Fonts associated with this mplot::Visual + mplot::VisualResources::i().freetype_deinit (this->visual_id); + } + + // Public init that is given a context (window or widget) and then sets up the + // VisualResource, shaders and so on. + void init (mplot::win_t* ctx) + { + this->window = ctx; + this->init_resources(); + this->init_gl(); + } + + // Do one-time init of the Visual's resources. This gets/creates the VisualResources, + // registers this visual with resources, calls init_window for any glfw stuff that needs to + // happen, and lastly initializes the freetype code. + void init_resources() + { + // VisualResources provides font management and GLFW management. Ensure it exists in memory. + mplot::VisualResources::i().create(); + this->visual_id = mplot::VisualResources::i().register_visual (this->glfn, this->window); + mplot::VisualResources::i().freetype_init (this->visual_id, this->glfn); + } + + /*! + * Add a VisualModel to the scene as a unique_ptr. The Visual object takes ownership of the + * unique_ptr. The index into Visual::vm is returned. + */ + template + std::uint32_t addVisualModelId (std::unique_ptr& model) + { + std::unique_ptr> vmp = std::move(model); + vmp->set_parent (this->visual_id); + if (vmp->instanced()) { this->state.set (visual_state::haveInstanced, true); } + this->vm.push_back (std::move(vmp)); + std::uint32_t rtn = (this->vm.size()-1); + return rtn; + } + + /*! + * Add a VisualModel to the scene as a unique_ptr. The Visual object takes ownership of the + * unique_ptr. A non-owning pointer to the model is returned. + */ + template + T* addVisualModel (std::unique_ptr& model) + { + std::unique_ptr> vmp = std::move(model); + vmp->set_parent (this->visual_id); + if (vmp->instanced()) { this->state.set (visual_state::haveInstanced, true); } + this->vm.push_back (std::move(vmp)); + return static_cast(this->vm.back().get()); + } + + /*! + * Test the pointer vmp. Return vmp if it is owned by a unique_ptr in + * Visual::vm. If it is not present, return nullptr. + */ + const mplot::VisualModel* validVisualModel (const mplot::VisualModel* vmp) const + { + const mplot::VisualModel* rtn = nullptr; + for (std::uint32_t modelId = 0; modelId < this->vm.size(); ++modelId) { + if (this->vm[modelId].get() == vmp) { + rtn = vmp; + break; + } + } + return rtn; + } + + /*! + * For the pointer vmp, if it is owned by a unique_ptr in Visual::vm, then return the index + * into Visual::vm at which it lives. This is its model ID. If it does not exist in + * Visual::vm, then return std::numeric_limits::max(). + */ + std::uint32_t getVisualModelId (const mplot::VisualModel* vmp) const + { + std::uint32_t rtn = std::numeric_limits::max(); + for (std::uint32_t modelId = 0; modelId < this->vm.size(); ++modelId) { + if (this->vm[modelId].get() == vmp) { + rtn = modelId; + break; + } + } + return rtn; + } + + void setFollowedVM (const mplot::VisualModel* vm_to_follow) + { + for (std::uint32_t modelId = 0; modelId < this->vm.size(); ++modelId) { + if (this->vm[modelId].get() == vm_to_follow) { + this->followedVM = this->vm[modelId].get(); + this->followedLastViewMatrix = this->followedVM->getViewMatrix(); + break; + } + } + } + + /*! + * VisualModel Getter + * + * For the given \a modelId, return a (non-owning) pointer to the visual model. + * + * \return VisualModel pointer + */ + mplot::VisualModel* getVisualModel (std::uint32_t modelId) { return (this->vm[modelId].get()); } + + //! Remove the VisualModel with ID \a modelId from the scene. + void removeVisualModel (std::uint32_t modelId) { this->vm.erase (this->vm.begin() + modelId); } + + //! Remove the VisualModel whose pointer matches the VisualModel* vmp + void removeVisualModel (mplot::VisualModel* vmp) + { + std::uint32_t modelId = 0; + bool found_model = false; + for (modelId = 0; modelId < this->vm.size(); ++modelId) { + if (this->vm[modelId].get() == vmp) { + found_model = true; + break; + } + } + if (found_model == true) { this->vm.erase (this->vm.begin() + modelId); } + } + + //! Remove the VisualModels in the vm stack from the one whose pointer matches the + //! VisualModel* vmp, to the end of the stack. + void removeVisualModels (mplot::VisualModel* vmp) + { + std::uint32_t modelId = 0; + bool found_model = false; + for (modelId = 0; modelId < this->vm.size(); ++modelId) { + if (this->vm[modelId].get() == vmp) { + found_model = true; + break; + } + } + if (found_model == true) { this->vm.erase (this->vm.begin() + modelId, this->vm.end()); } + } + + void clear () { this->vm.clear(); } + + void set_cursorpos (double _x, double _y) { this->cursorpos = {static_cast(_x), static_cast(_y)}; } + + //! A callback function + static void callback_render (mplot::VisualOwnable* _v) { _v->render(); }; + + //! GLAD OpenGL function context pointer. A copy is stored in VisualResources. + GladGLContext* glfn = nullptr; + + //! Stores the OpenGL function context version that was loaded + std::int32_t glfn_version = 0; + + //! Graphics context functions that refer to the window system (GLFW usually) are defined in derived class + virtual void setContext() = 0; + virtual void releaseContext() = 0; + virtual void swapBuffers() = 0; + virtual void setSwapInterval() = 0; + + //! Take a screenshot of the window. Return vec containing width * height or {-1, -1} on + //! failure. Set transparent_bg to get a transparent background. + sm::vec saveImage (const std::string& img_filename, const bool transparent_bg = false) + { + using namespace std::chrono; + using sc = std::chrono::steady_clock; + constexpr bool profile_saveimage = false; + sc::time_point t0, t1, t2; + + this->setContext(); + + if constexpr (profile_saveimage) { t0 = sc::now(); } + + std::int32_t viewport[4]; // current viewport + this->glfn->GetIntegerv (GL_VIEWPORT, viewport); + + sm::vec dims; + dims[0] = viewport[2]; + dims[1] = viewport[3]; + auto bits = std::make_unique(dims.product() * 4); + auto rbits = std::make_unique(dims.product() * 4); + + this->glfn->Finish(); // finish all commands of OpenGL + this->glfn->PixelStorei (GL_PACK_ALIGNMENT, 1); + this->glfn->PixelStorei (GL_PACK_ROW_LENGTH, 0); + this->glfn->PixelStorei (GL_PACK_SKIP_ROWS, 0); + this->glfn->PixelStorei (GL_PACK_SKIP_PIXELS, 0); + this->glfn->ReadPixels (0, 0, dims[0], dims[1], GL_RGBA, GL_UNSIGNED_BYTE, bits.get()); + + for (std::int32_t i = 0; i < dims[1]; ++i) { + std::int32_t rev_line = (dims[1] - i - 1) * 4 * dims[0]; + std::int32_t for_line = i * 4 * dims[0]; + if (transparent_bg) { + for (std::int32_t j = 0; j < 4 * dims[0]; ++j) { + rbits[rev_line + j] = bits[for_line + j]; + } + } else { + for (std::int32_t j = 0; j < 4 * dims[0]; ++j) { + rbits[rev_line + j] = (j % 4 == 3) ? 255 : bits[for_line + j]; + } + } + } + + if constexpr (profile_saveimage) { t1 = sc::now(); } + + std::uint32_t error = 0; + + // If filename ends with pnm, then save in pnm format; otherwise save as PNG + bool pnm_save = false; + if (img_filename.find ("pnm") == img_filename.size() - 3) { pnm_save = true; } + if (pnm_save == true) { + error = mplot::pnm_encode (img_filename, rbits.get(), dims[0], dims[1]); + } else { + error = mplot::png_encode (img_filename, rbits.get(), dims[0], dims[1]); // Need alternative + } + + if constexpr (profile_saveimage) { + t2 = sc::now(); + sc::duration t_d = t1 - t0; + sc::duration t_d2 = t2 - t1; + std::cout << "Bit-collection: " << duration_cast(t_d).count() << " ms" + << " and png/pnm_encode: " << duration_cast(t_d2).count() << " ms\n"; + } + + if (error) { + if (pnm_save == true) { + std::cerr << "pnm encoder error " << error << std::endl; + } else { + std::cerr << "encoder error " << error << ": " << mplot::png_error_text (error) << std::endl; + } + dims.set_from (-1); + return dims; + } + return dims; + } + + //! Render the scene + void render() noexcept + { + ++this->render_counter; + + this->setContext(); + + this->glfn->UseProgram (this->shaders.gprog); + this->glfn->Viewport (0, 0, this->window_w * this->window_scale_w, this->window_h * this->window_scale_h); + + // Set the perspective + if (this->ptype == perspective_type::orthographic) { + this->setOrthographic(); + } else if (this->ptype == perspective_type::perspective) { + this->setPerspective(); + } else { + // unknown projection + return; + } + + // Calculate model view transformation - transforming from "model space" to "worldspace". + this->computeSceneview(); + + // Clear color buffer and **also depth buffer** + this->glfn->Clear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + // Set the background colour: + this->glfn->ClearBufferfv (GL_COLOR, 0, this->bgcolour.data()); + + // Lighting shader variables + // + // Ambient light colour + GLint loc_lightcol = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("light_colour")); + if (loc_lightcol != -1) { this->glfn->Uniform3fv (loc_lightcol, 1, this->light_colour.data()); } + // Ambient light intensity + GLint loc_ai = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("ambient_intensity")); + if (loc_ai != -1) { this->glfn->Uniform1f (loc_ai, this->ambient_intensity); } + // Diffuse light position + GLint loc_dp = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("diffuse_position")); + if (loc_dp != -1) { this->glfn->Uniform3fv (loc_dp, 1, this->diffuse_position.data()); } + // Diffuse light intensity + GLint loc_di = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("diffuse_intensity")); + if (loc_di != -1) { this->glfn->Uniform1f (loc_di, this->diffuse_intensity); } + + // Switch to text shader program and set the projection matrix + this->glfn->UseProgram (this->shaders.tprog); + GLint loc_p = this->glfn->GetUniformLocation (this->shaders.tprog, static_cast("p_matrix")); + if (loc_p != -1) { this->glfn->UniformMatrix4fv (loc_p, 1, GL_FALSE, this->projection.arr.data()); } + + // Switch back to the regular shader prog and render the VisualModels. + this->glfn->UseProgram (this->shaders.gprog); + + // Set the projection matrix just once + loc_p = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("p_matrix")); + if (loc_p != -1) { this->glfn->UniformMatrix4fv (loc_p, 1, GL_FALSE, this->projection.arr.data()); } + + if ((this->ptype == perspective_type::orthographic || this->ptype == perspective_type::perspective) + && this->options.test (visual_options::showCoordArrows)) { + // Ensure coordarrows centre sphere will be visible on BG: + this->coordArrows->setColourForBackground (this->bgcolour); // releases context... + this->setContext(); // ...so re-acquire if we're managing it + + if (this->options.test (visual_options::coordArrowsInScene) == true) { + this->coordArrows->setSceneMatrix (this->sceneview); + } else { + this->positionCoordArrows(); + } + this->coordArrows->render(); + } + + if (this->haveInstanced() && mplot::VisualResources::i().get_instanced_needs_update (this->visual_id)) { + mplot::VisualResources::i().copy_instance_ssbo_to_gpu(); + mplot::VisualResources::i().instanced_needs_update (this->visual_id, false); + } + + auto vmi = this->vm.begin(); + while (vmi != this->vm.end()) { + if ((*vmi)->twodimensional() == true) { + // It's a two-d thing. Use the companion 'scene trans only' matrix, which avoids any rotations + (*vmi)->setSceneMatrix (this->sceneview_tr); + } else { + (*vmi)->setSceneMatrix (this->sceneview); + } + (*vmi)->render(); + ++vmi; + } + + sm::vec v0 = this->textPosition ({-0.8f, 0.8f}); + if (this->options.test (visual_options::showTitle) == true) { + // Render the title text + this->textModel->setSceneTranslation (v0); + this->textModel->setVisibleOn (this->bgcolour); + this->textModel->render(); + } + + auto ti = this->texts.begin(); + while (ti != this->texts.end()) { + (*ti)->setSceneTranslation (v0); + (*ti)->setVisibleOn (this->bgcolour); + (*ti)->render(); + ++ti; + } + + if (this->options.test (visual_options::renderSwapsBuffers) == true) { + this->swapBuffers(); + } + } + + //! Compute a translation vector for text position, using Visual::text_z. + sm::vec textPosition (const sm::vec p0_coord) + { + // For the depth at which a text object lies, use this->text_z. Use forward + // projection to determine the correct z coordinate for the inverse + // projection. + sm::vec point = { 0.0f, 0.0f, this->text_z, 1.0f }; + sm::vec pp = this->projection * point; + float coord_z = pp[2]/pp[3]; // divide by pp[3] is divide by/normalise by 'w'. + // Construct the point for the location of the text + sm::vec p0 = { p0_coord.x(), p0_coord.y(), coord_z, 1.0f }; + // Inverse project the point + sm::vec v0; + v0.set_from (this->invproj * p0); + return v0; + } + + protected: + // GLAD specific gl context creation/freeing. GladGLContext is a struct containing + GladGLContext* create_gladgl_context (const GLADloadfunc procaddressfn) + { + GladGLContext* context = (GladGLContext*) calloc(1, sizeof(GladGLContext)); + if (!context) { return nullptr; } + this->glfn_version = gladLoadGLContext (context, procaddressfn); + // ...so glfn_version should (more or less) match the version specified in the glver + // template arg + return context; + } + void free_gladgl_context (GladGLContext *context) + { + if (context) { free(context); } + context = nullptr; + } + + public: + void init_glad (GLADloadfunc procaddressfn) + { + // Create the OpenGL function context - a GladGLContext* + this->glfn = this->create_gladgl_context (procaddressfn); + + if (!this->glfn) { + std::cout << "Failed to initialize GLAD GL context" << std::endl; + this->free_gladgl_context (this->glfn); + } + } + + //! Add a label _text to the scene at position _toffset. Font features are + //! defined by the tf. Return geometry of the text. + mplot::TextGeometry addLabel (const std::string& _text, + const sm::vec& _toffset, + const mplot::TextFeatures& tf = mplot::TextFeatures(0.01f)) + { + this->setContext(); + if (this->shaders.tprog == 0) { throw std::runtime_error ("No text shader prog."); } + auto tmup = std::make_unique> (tf); + tmup->set_parent (this->visual_id); + if (tf.centre_horz == true) { + mplot::TextGeometry tg = tmup->getTextGeometry(_text); + sm::vec centred_locn = _toffset; + centred_locn[0] = -tg.half_width(); + tmup->setupText (_text, centred_locn, tf.colour); + } else { + tmup->setupText (_text, _toffset, tf.colour); + } + mplot::VisualTextModel* tm = tmup.get(); + this->texts.push_back (std::move(tmup)); + this->releaseContext(); + return tm->getTextGeometry(); + } + + //! Add a label _text to the scene at position _toffset. Font features are + //! defined by the tf. Return geometry of the text. The pointer tm is a + //! return value that allows client code to change the text after the label has been added. + mplot::TextGeometry addLabel (const std::string& _text, + const sm::vec& _toffset, + mplot::VisualTextModel*& tm, + const mplot::TextFeatures& tf = mplot::TextFeatures(0.01f)) + { + this->setContext(); + if (this->shaders.tprog == 0) { throw std::runtime_error ("No text shader prog."); } + auto tmup = std::make_unique> (tf); + tmup->set_parent (this->visual_id); + if (tf.centre_horz == true) { + mplot::TextGeometry tg = tmup->getTextGeometry(_text); + sm::vec centred_locn = _toffset; + centred_locn[0] = -tg.half_width(); + tmup->setupText (_text, centred_locn, tf.colour); + } else { + tmup->setupText (_text, _toffset, tf.colour); + } + tm = tmup.get(); + this->texts.push_back (std::move(tmup)); + this->releaseContext(); + return tm->getTextGeometry(); + } + + protected: + // Initialize OpenGL shaders, set some flags (Alpha, Anti-aliasing) and set up the + // coordinate arrows and any VisualTextModels that will be required to render the Visual. + void init_gl() + { + this->setContext(); // if managing context + + if (this->options.test (visual_options::versionStdout) == true) { + std::uint8_t* glv = (std::uint8_t*)this->glfn->GetString(GL_VERSION); + std::cout << "This is version " << mplot::version_string() + << " of mplot::Visual running on OpenGL Version " << glv << std::endl; + } + + this->setSwapInterval(); + + // Load up the shaders + this->proj2d_shader_progs = { + {GL_VERTEX_SHADER, "Visual.vert.glsl", mplot::getDefaultVtxShader(glver), 0 }, + {GL_FRAGMENT_SHADER, "Visual.frag.glsl", mplot::getDefaultFragShader(glver), 0 } + }; + this->shaders.gprog = mplot::gl::LoadShadersMX (this->proj2d_shader_progs, this->glfn); + mplot::VisualResources::i().set_gprog (this->visual_id, this->shaders.gprog); + + // A specific text shader is loaded for text rendering + this->text_shader_progs = { + {GL_VERTEX_SHADER, "VisText.vert.glsl", mplot::getDefaultTextVtxShader(glver), 0 }, + {GL_FRAGMENT_SHADER, "VisText.frag.glsl" , mplot::getDefaultTextFragShader(glver), 0 } + }; + this->shaders.tprog = mplot::gl::LoadShadersMX (this->text_shader_progs, this->glfn); + mplot::VisualResources::i().set_tprog (this->visual_id, this->shaders.tprog); + + // OpenGL options + this->glfn->Enable (GL_DEPTH_TEST); + this->glfn->Enable (GL_BLEND); + this->glfn->BlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + this->glfn->Disable (GL_CULL_FACE); + mplot::gl::Util::checkError (__FILE__, __LINE__, this->glfn); + + // Use coordArrowsOffset to set the location of the CoordArrows *scene* + this->coordArrows = std::make_unique>(); + this->coordArrows->set_parent (this->visual_id); + // And NOW we can proceed to init (lengths, thickness, em size for labels): + this->coordArrows->init (sm::vec<>{0.1f, 0.1f, 0.1f}, 1.0f, 0.01f); + this->coordArrows->finalize(); // VisualModel::finalize releases context (normally this is the right thing)... + this->setContext(); // ...but we've got more work to do, so re-acquire context (if we're managing it) + + mplot::gl::Util::checkError (__FILE__, __LINE__, this->glfn); + + // Set up the title, which may or may not be rendered + mplot::TextFeatures title_tf(0.035f, 64); + this->textModel = std::make_unique> (title_tf); + this->textModel->set_parent (this->visual_id); + this->textModel->setSceneTranslation ({0.0f, 0.0f, 0.0f}); + this->textModel->setupText (this->title); + + this->releaseContext(); + } + + //! A VisualTextModel for a title text. + std::unique_ptr> textModel = nullptr; + //! Text models for labels + std::vector>> texts; + + public: + //! The OpenGL shader programs have an integer ID and are stored in a simple struct. There's + //! one for graphical objects and a text shader program, which uses textures to draw text on + //! quads. + mplot::visgl::visual_shaderprogs shaders; // stored in VisualResources too. + + //! Stores the info required to load the 2D projection shader + std::vector proj2d_shader_progs; + //! Stores the info required to load the text shader + std::vector text_shader_progs; + + //! The colour of ambient and diffuse light sources + sm::vec light_colour = { 1.0f, 1.0f, 1.0f }; + //! Strength of the ambient light + float ambient_intensity = 1.0f; + //! Position of a diffuse light source + sm::vec diffuse_position = { 5.0f, 5.0f, 15.0f }; + //! Strength of the diffuse light source + float diffuse_intensity = 0.0f; + + // Track how many calls to render have been made. At 1000 FPS this overflows at 10^17 seconds which is about 10^9 years. + std::uint64_t render_counter = 0u; + // A move counter. May be incremented in step with render_counter, or it may not (for example, it may restart) + std::uint64_t move_counter = 0u; + + //! Compute position and rotation of coordinate arrows in the bottom left of the screen + void positionCoordArrows() + { + // Find out the location of the bottom left of the screen and make the coord + // arrows stay put there. + + // Add the depth at which the object lies. Use forward projection to determine the + // correct z coordinate for the inverse projection. This assumes only one object. + sm::vec point = { 0.0f, 0.0f, this->sceneview[14], 1.0f }; // sceneview[14] is 'scenetrans.z' + sm::vec pp = this->projection * point; + float coord_z = pp[2]/pp[3]; // divide by pp[3] is divide by/normalise by 'w'. + + // Construct the point for the location of the coord arrows + sm::vec p0 = { this->coordArrowsOffset.x(), this->coordArrowsOffset.y(), coord_z, 1.0f }; + // Inverse project + sm::vec v0; + v0.set_from ((this->invproj * p0)); + // Translate the scene for the CoordArrows such that they sit in a single position on + // the screen + this->coordArrows->setSceneTranslation (v0); + // Apply rotation to the coordArrows model + sm::quaternion svrq = this->sceneview.rotation(); + svrq.renormalize(); + this->coordArrows->setViewRotation (svrq); + } + + // Update the coordinate axes labels + void updateCoordLabels (const std::string& x_lbl, const std::string& y_lbl, const std::string& z_lbl) + { + this->coordArrows->clear(); + this->coordArrows->x_label = x_lbl; + this->coordArrows->y_label = y_lbl; + this->coordArrows->z_label = z_lbl; + this->coordArrows->initAxisLabels(); + this->coordArrows->reinit(); + } + + // Update the lengths of the CoordArrows that (usually) appear in the corner of the screen + void updateCoordLengths (const sm::vec& _lengths, const float _thickness = 1.0f) + { + this->coordArrows->lengths = _lengths; + this->coordArrows->thickness = _thickness; + this->coordArrows->clear(); + this->coordArrows->initAxisLabels(); + this->coordArrows->reinit(); + } + + // state defaults. All state is false by default + constexpr sm::flags state_defaults() + { + sm::flags _state; + return _state; + } + + // State flags + sm::flags state = state_defaults(); + + // Options defaults. + constexpr sm::flags options_defaults() + { + sm::flags _options; + // Only with ImGui do we manually swap buffers, so this is true by default: + _options.set (visual_options::renderSwapsBuffers); + // For now, default to rotating about scene origin, as we ever did (Ctrl-k to change) + _options.set (visual_options::rotateAboutSceneOrigin); + // Also, for now, keep the Blender-like 'rotateAboutVertical' as a non-default option (Ctrl-d to change) + _options.set (visual_options::rotateAboutVertical, false); + + return _options; + } + + // Option flags + sm::flags options = options_defaults(); + + //! Returns true when the program has been flagged to end + bool readyToFinish() const { return this->state.test (visual_state::readyToFinish); } + + //! Returns true if we are in the paused state + bool paused() const { return this->state.test (visual_state::paused); } + + //! True if one of our added VisualModels is an instanced model + bool haveInstanced() const { return this->state.test (visual_state::haveInstanced); } + + /* + * User-settable projection values for the near clipping distance, the far clipping distance + */ + float zNear = 0.001f; + float zFar = 300.0f; + + /* + * User settable field of view of the camera in degrees. Note that the field of view is + * measured from the top of the field to the bottom of the field (rather than from the left + * to the right). + */ + float fov = 30.0f; + + //! Setter for fov + void set_vertical_fov (const float vfov) { this->fov = vfov; } + //! Setter for fov, if you want to specify horizontal field of view + void set_horizontal_fov (const float hfov) + { + float aspect = static_cast(this->window_w) / static_cast(this->window_h ? this->window_h : 1); + this->fov = hfov / aspect; + } + + //! Time constants for the way the camera moves between a follow-me view and a + //! drone-view. One for translation, the other for rotation. + float trans_tc = 0.09f; + //! Rotational time constant + float rotn_tc = trans_tc; + + //! Which was is up in the scene? In OpenGL it's usually y, but may be changed to z in some cases + sm::vec scene_up = sm::vec::uy(); + //! Which way goes to the 'right' across the screen? Usually x + sm::vec scene_right = sm::vec::ux(); + //! Out of the screen? + sm::vec scene_out = sm::vec::uz(); + + //! Setter for visual_options::showCoordArrows + void showCoordArrows (const bool val) { this->options.set (visual_options::showCoordArrows, val); } + + //! If true, then place the coordinate arrows at the origin of the scene, rather than offset. + void coordArrowsInScene (const bool val) { this->options.set (visual_options::coordArrowsInScene, val); } + + //! Rotate about the nearest VisualModel? + void rotateAboutNearest (const bool val) + { this->options.set (mplot::visual_options::rotateAboutSceneOrigin, (val ? false : true)); } + + //! Rotate about a vertical axis in the scene? + void rotateAboutVertical (const bool val) { this->options.set (visual_options::rotateAboutVertical, val); } + + //! Set to true to show the title text within the scene + void showTitle (const bool val) { this->options.set (visual_options::showTitle, val); } + + //! Set true to output some user information to stdout (e.g. user requested quit) + void userInfoStdout (const bool val) { this->options.set (visual_options::userInfoStdout, val); } + + //! You can call this with val==false to manage exactly when you call the swapBuffer() method (for ImGui programs) + void renderSwapsBuffers (const bool val) { this->options.set (visual_options::renderSwapsBuffers, val); } + + //! How big should the steps in scene translation be when scrolling? + float scenetrans_stepsize = 0.02f; + + //! If you set this to true, then the mouse movements won't change scenetrans or rotation. + void sceneLocked (const bool val) { this->state.set (visual_state::sceneLocked, val); } + + //! Show bounding boxes? + void showBoundingBoxes (const bool val) { this->options.set (visual_options::showBoundingBoxes, val); } + + //! Highlight (with a bounding box) the VisualModel being used for rotation? + void highlightRotationVM (const bool val) { this->options.set (visual_options::highlightRotationVM, val); } + + //! Can change this to orthographic + perspective_type ptype = perspective_type::perspective; + + //! Orthographic screen left-bottom coordinate (you can change these to encapsulate your models) + sm::vec ortho_lb = { -1.3f, -1.0f }; + //! Orthographic screen right-top coordinate + sm::vec ortho_rt = { 1.3f, 1.0f }; + + //! The background colour; white by default. + std::array bgcolour = { 1.0f, 1.0f, 1.0f, 0.5f }; + + /* + * User can directly set bgcolour for any background colour they like, but + * here are convenience functions: + */ + + //! Set a white background colour for the Visual scene + void backgroundWhite() { this->bgcolour = { 1.0f, 1.0f, 1.0f, 0.5f }; } + //! Set a black background colour for the Visual scene + void backgroundBlack() { this->bgcolour = { 0.0f, 0.0f, 0.0f, 0.0f }; } + + //! Set sceneview and sceneview_tr back to scenetrans_default + void reset_sceneviews_to_scenetrans_default() + { + this->sceneview.set_identity(); + this->sceneview.translate (this->scenetrans_default); + this->sceneview_tr.set_identity(); + this->sceneview_tr.translate (this->scenetrans_default); + this->d_to_rotation_centre = -this->scenetrans_default[2]; + } + + void setSceneview (const sm::mat& sv) + { + this->lastSceneview = this->sceneview; + this->sceneview = sv; + this->sceneview_tr.set_identity(); + this->sceneview_tr.translate (sv.translation()); + } + + //! Set the scene's x and y values at the same time. + void setSceneTransXY (const float _x, const float _y) + { + this->scenetrans_default[0] = _x; + this->scenetrans_default[1] = _y; + this->reset_sceneviews_to_scenetrans_default(); + } + //! Set the scene's y value. Use this to shift your scene objects left or right + void setSceneTransX (const float _x) + { + this->scenetrans_default[0] = _x; + this->reset_sceneviews_to_scenetrans_default(); + } + //! Set the scene's y value. Use this to shift your scene objects up and down + void setSceneTransY (const float _y) + { + this->scenetrans_default[1] = _y; + this->reset_sceneviews_to_scenetrans_default(); + } + //! Set the scene's z value. Use this to bring the 'camera' closer to your scene + //! objects (that is, your mplot::VisualModel objects). + void setSceneTransZ (const float _z) + { + if (_z > 0.0f) { + std::cerr << "WARNING setSceneTransZ(): Normally, the default z value is negative.\n"; + } + this->scenetrans_default[2] = _z; + this->reset_sceneviews_to_scenetrans_default(); + } + void setSceneTrans (float _x, float _y, float _z) + { + if (_z > 0.0f) { + std::cerr << "WARNING setSceneTrans(): Normally, the default z value is negative.\n"; + } + + this->scenetrans_default[0] = _x; + this->scenetrans_default[1] = _y; + this->scenetrans_default[2] = _z; + this->reset_sceneviews_to_scenetrans_default(); + } + void setSceneTrans (const sm::vec& _xyz) + { + if (_xyz[2] > 0.0f) { + std::cerr << "WARNING setSceneTrans(vec<>&): Normally, the default z value is negative.\n"; + } + this->scenetrans_default = _xyz; + this->reset_sceneviews_to_scenetrans_default(); + } + + void setSceneRotation (const sm::quaternion& _rotn) + { + this->rotation_default = _rotn; + this->sceneview.rotate (_rotn); + } + + // What is the scene view's current rotation quaternion? + sm::quaternion getSceneRotation() const { return this->sceneview.rotation(); } + // What is the scene view's current translation? + sm::vec getSceneTranslation() const { return this->sceneview.translation(); } + + // API for client code to set a 'film direction' event. This may change the sceneview + // immediately, or start a timed sequence of changes to animate the sceneview. + void setCurrentDirectionEvent (const mplot::direction_data& dirn) + { + constexpr bool debug_dirn_event = false; + + // timed translation/rotation/transform are all 'viewAutomations' + this->state.set (visual_state::viewAutomation); + this->currentAutoSceneviewChange = dirn; + this->currentAutoSceneviewChange.start_frame = this->render_counter; + if constexpr (debug_dirn_event) { + std::cout << __func__ << " event id " << this->currentAutoSceneviewChange.id + << " starting at frame " << this->currentAutoSceneviewChange.start_frame << std::endl; + } + // Auto translation behaves like a mouse-press then mouse-drag; computing a delta from a savedSceneview + this->savedSceneview = this->sceneview; + this->savedSceneview_tr = this->sceneview_tr; + this->scenetrans_delta.zero(); + this->rotation_delta.reset(); + // If it's a rotation event, also need a rotation centre + if (dirn.event == direction_event::timed_rotation) { + this->find_rotation_centre(); + } else if (dirn.event == direction_event::timed_transform) { + // Find the start and end translation + this->currentAutoSceneviewChange.translation = dirn.sceneview.translation() - this->sceneview.translation(); + // Find the start and end rotation + this->currentAutoSceneviewChange.rotation_start = this->sceneview.rotation(); // rotation at start + this->currentAutoSceneviewChange.rotation_start.renormalize(); + this->currentAutoSceneviewChange.rotation = dirn.sceneview.rotation(); // rotation at end + this->currentAutoSceneviewChange.rotation.renormalize(); + this->find_rotation_centre(); + } else if (dirn.event == direction_event::sceneview) { + std::cout << "Set a sceneview event for current direction event" << std::endl; + // An immediate sceneview event is just a timed_transform with the time for the transform set to 1 + this->currentAutoSceneviewChange.transform_time_frames = 2u; + this->currentAutoSceneviewChange.min_jerk = false; + // Find the start and end translation + this->currentAutoSceneviewChange.translation = dirn.sceneview.translation() - this->sceneview.translation(); + // Find the start and end rotation + this->currentAutoSceneviewChange.rotation_start = this->sceneview.rotation(); // rotation at start + this->currentAutoSceneviewChange.rotation_start.renormalize(); + this->currentAutoSceneviewChange.rotation = dirn.sceneview.rotation(); // rotation at end + this->currentAutoSceneviewChange.rotation.renormalize(); + this->find_rotation_centre(); + } else if (dirn.event == direction_event::timed_orbit) { + // Might need this: + this->currentAutoSceneviewChange.translation = dirn.sceneview.translation() - this->sceneview.translation(); + } + } + + void lightingEffects (const bool effects_on = true) + { + this->ambient_intensity = effects_on ? 0.4f : 1.0f; + this->diffuse_intensity = effects_on ? 0.6f : 0.0f; + } + + //! Save all the VisualModels in this Visual out to a GLTF format file + virtual void savegltf (const std::string& gltf_file) + { + std::ofstream fout (gltf_file, std::ios::out|std::ios::trunc); + if (!fout.is_open()) { throw std::runtime_error ("Visual::savegltf(): Failed to open file for writing"); } + fout << "{\n \"scenes\" : [ { \"nodes\" : [ "; + for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { + fout << vmi << (vmi < this->vm.size()-1 ? ", " : ""); + } + fout << " ] } ],\n"; + + fout << " \"nodes\" : [\n"; + // for loop over VisualModels "mesh" : 0, etc + for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { + fout << " { \"mesh\" : " << vmi + << ", \"translation\" : " << this->vm[vmi]->translation_str() + << (vmi < this->vm.size()-1 ? " },\n" : " }\n"); + } + fout << " ],\n"; + + fout << " \"meshes\" : [\n"; + // for each VisualModel: + for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { + fout << " { "; + if (!this->vm[vmi]->name.empty()) { + fout << "\"name\" : \"" << this->vm[vmi]->name << "\", "; + } + fout << "\"primitives\" : [ { \"attributes\" : { \"POSITION\" : " << 1+vmi*4 + << ", \"COLOR_0\" : " << 2+vmi*4 + << ", \"NORMAL\" : " << 3+vmi*4 << " }, \"indices\" : " << vmi*4 << ", \"material\": 0 } ] }" + << (vmi < this->vm.size()-1 ? ",\n" : "\n"); + } + fout << " ],\n"; + + fout << " \"buffers\" : [\n"; + for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { + // indices + fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->indices_base64() << "\", " + << "\"byteLength\" : " << this->vm[vmi]->indices_bytes() << "},\n"; + // pos + fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->vpos_base64() << "\", " + << "\"byteLength\" : " << this->vm[vmi]->vpos_bytes() << "},\n"; + // col + fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->vcol_base64() << "\", " + << "\"byteLength\" : " << this->vm[vmi]->vcol_bytes() << "},\n"; + // norm + fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->vnorm_base64() << "\", " + << "\"byteLength\" : " << this->vm[vmi]->vnorm_bytes() << "}"; + fout << (vmi < this->vm.size()-1 ? ",\n" : "\n"); + } + fout << " ],\n"; + + fout << " \"bufferViews\" : [\n"; + for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { + // indices + fout << " { "; + fout << "\"buffer\" : " << vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + fout << "\"byteLength\" : " << this->vm[vmi]->indices_bytes() << ", "; + fout << "\"target\" : 34963 "; + fout << " },\n"; + // vpos + fout << " { "; + fout << "\"buffer\" : " << 1+vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + fout << "\"byteLength\" : " << this->vm[vmi]->vpos_bytes() << ", "; + fout << "\"target\" : 34962 "; + fout << " },\n"; + // vcol + fout << " { "; + fout << "\"buffer\" : " << 2+vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + fout << "\"byteLength\" : " << this->vm[vmi]->vcol_bytes() << ", "; + fout << "\"target\" : 34962 "; + fout << " },\n"; + // vnorm + fout << " { "; + fout << "\"buffer\" : " << 3+vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + fout << "\"byteLength\" : " << this->vm[vmi]->vnorm_bytes() << ", "; + fout << "\"target\" : 34962 "; + fout << " }"; + fout << (vmi < this->vm.size()-1 ? ",\n" : "\n"); + } + fout << " ],\n"; + + fout << " \"accessors\" : [\n"; + for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { + this->vm[vmi]->computeVertexMaxMins(); + // indices + fout << " { "; + fout << "\"bufferView\" : " << vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + // 5123 unsigned short, 5121 unsigned byte, 5125 unsigned int, 5126 float: + fout << "\"componentType\" : 5125, "; + fout << "\"type\" : \"SCALAR\", "; + fout << "\"count\" : " << this->vm[vmi]->indices_size(); + fout << "},\n"; + // vpos + fout << " { "; + fout << "\"bufferView\" : " << 1+vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + fout << "\"componentType\" : 5126, "; + fout << "\"type\" : \"VEC3\", "; + fout << "\"count\" : " << this->vm[vmi]->vpos_size()/3; + // vertex position requires max/min to be specified in the gltf format + fout << ", \"max\" : " << this->vm[vmi]->vpos_max() << ", "; + fout << "\"min\" : " << this->vm[vmi]->vpos_min(); + fout << " },\n"; + // vcol + fout << " { "; + fout << "\"bufferView\" : " << 2+vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + fout << "\"componentType\" : 5126, "; + fout << "\"type\" : \"VEC3\", "; + fout << "\"count\" : " << this->vm[vmi]->vcol_size()/3; + fout << "},\n"; + // vnorm + fout << " { "; + fout << "\"bufferView\" : " << 3+vmi*4 << ", "; + fout << "\"byteOffset\" : 0, "; + fout << "\"componentType\" : 5126, "; + fout << "\"type\" : \"VEC3\", "; + fout << "\"count\" : " << this->vm[vmi]->vnorm_size()/3; + fout << "}"; + fout << (vmi < this->vm.size()-1 ? ",\n" : "\n"); + } + fout << " ],\n"; + + // Default material is single sided, so make it double sided + fout << " \"materials\" : [ { \"doubleSided\" : true } ],\n"; + + fout << " \"asset\" : {\n" + << " \"generator\" : \"https://github.com/sebsjames/mathplot: mplot::Visual::savegltf() (ver " + << mplot::version_string() << ")\",\n" + << " \"version\" : \"2.0\"\n" // This version is the *glTF* version. + << " }\n"; + fout << "}\n"; + fout.close(); + } + + void set_winsize (const std::int32_t _w, const std::int32_t _h) { this->window_w = _w; this->window_h = _h; } + + // Accessing std::vector>> vm; from external code + std::vector>>::const_iterator next_vm_accessor; + void init_vm_accessor() { this->next_vm_accessor = this->vm.begin(); } + mplot::VisualModel* get_next_vm_accessor() + { + mplot::VisualModel* cvm = nullptr; + if (this->next_vm_accessor != this->vm.end()) { + cvm = (*this->next_vm_accessor).get(); + this->next_vm_accessor++; + } + return cvm; + } + + std::uint32_t get_id() const { return this->visual_id; } + + protected: + + //! Set up a perspective projection based on window width and height. Not public. + void setPerspective() + { + // Calculate aspect ratio + float aspect = static_cast(this->window_w) / static_cast(this->window_h ? this->window_h : 1); + // Set perspective projection + this->projection = sm::mat::perspective (this->fov, aspect, this->zNear, this->zFar); + // Compute the inverse projection matrix + this->invproj = this->projection.inverse(); + } + + /*! + * Set an orthographic projection. This is not a public function. To choose orthographic + * projection for your Visual, write something like: + * + * \code + * mplot::Visual<> v(width, height, title); + * v.ptype = mplot::perspective_type::orthographic; + * \endcode + */ + void setOrthographic() + { + this->projection = sm::mat::orthographic (this->ortho_lb, this->ortho_rt, this->zNear, this->zFar); + this->invproj = this->projection.inverse(); + } + + // Rotate about the point this->rotation_centre. Subroutine for computeSceneview. + void computeSceneview_about_rotation_centre() + { + sm::mat sv_tr = sm::mat::identity(); + sm::mat sv_rot = sm::mat::identity(); + sv_tr.translate (this->scenetrans_delta); + // A rotation delta in world frame about the 'screen centre' + sv_rot.translate (this->rotation_centre); + sv_rot.rotate (this->rotation_delta); + sv_rot.translate (-this->rotation_centre); + + this->sceneview = sv_tr * sv_rot * this->savedSceneview; + this->sceneview_tr = sv_tr * this->savedSceneview_tr; + } + + // Get a camera movement that moves us nearer to target. + template + sm::vec get_cam_movement (sm::mat& current, const sm::mat& target, + sm::vec& vel, const T tc) const + { + const sm::vec delta = target.translation() - current.translation(); + const sm::vec force = delta - (vel * T{2}); + sm::vec pos_shift = vel * tc; + vel += force * tc; + return pos_shift; + } + + template + sm::quaternion get_cam_rotation (const sm::quaternion& r_cur0, const sm::mat& target, + T& rvel, const T tc) const + { + sm::mat target0 = target; + target0.translate (-target.translation()); + sm::quaternion r_targ0 = target0.rotation(); + r_targ0.renormalize(); + + sm::quaternion r_sz = r_targ0 * r_cur0.inverse(); + sm::vec aa = r_sz.axis_angle(); + T delta = aa[3]; // The angle subtended by the rotation + T force = delta - (rvel * T{2}); + // rvel is radpersec delta/tc + T prop = rvel * tc; + rvel += force * tc; + if (r_cur0.checkunit() == false) { throw std::runtime_error ("r_cur0 is not a unit quaternion (could renormalize here)"); } + sm::quaternion newpos = r_cur0.slerp (r_targ0, prop); + return newpos; // rather than prop, as in get_cam_movement + } + + void switch_view_follows_mode() + { + // Relevant only if there is a followedVM + if (this->followedVM == nullptr) { return; } + + if (this->options.test (visual_options::viewFollowsVMBehind) == true + && this->options.test (visual_options::viewFollowsVMTranslations) == false) { + this->options.reset (visual_options::viewFollowsVMBehind); + this->options.set (visual_options::viewFollowsVMTranslations); + this->state.set (visual_state::viewFollowsModeChanged); + std::cout << "sceneview follows agent movements (overview)\n"; + } else { // this->options.test (mplot::visual_options::viewFollowsVMTranslations) == true + this->options.set (visual_options::viewFollowsVMBehind); + this->state.set (visual_state::viewFollowsModeChanged); + this->options.reset (visual_options::viewFollowsVMTranslations); + std::cout << "sceneview follows behind agent (follower view)\n"; + } + } + + // Compile-time function to create a rotate-about-y transform + static constexpr sm::mat rotate_about_y() + { + sm::mat r = sm::mat::identity(); + r.rotate (sm::vec<>::uy(), sm::mathconst::pi); + return r; + } + + // Hold an offset translation and rotation for the follow-me camera + static constexpr sm::vec folcam_offset_tr_default = {0, 0.01f, -0.06f}; + sm::vec folcam_offset_tr = folcam_offset_tr_default; + sm::quaternion folcam_offset_rot; + + sm::mat update_viewmatrix_towards_target (const sm::mat& target) + { + sm::mat fol_cur = sm::mat::identity(); + + // Compute folcam_viewmatrix from sceneview (it's the inverse, along with a rotation) + constexpr sm::mat rotn_y = rotate_about_y(); + sm::mat folcam_viewmatrix = this->sceneview.inverse() * rotn_y; + + const sm::vec folcam_vm_trans = folcam_viewmatrix.translation(); + + fol_cur.translate (folcam_vm_trans); // encode just the location of the following camera + + // The current rotation of the scene view + folcam_viewmatrix.translate (-folcam_vm_trans); + sm::quaternion r_cur0 = folcam_viewmatrix.rotation(); + r_cur0.renormalize(); + + // get_cam_movement computes the positional shift + sm::vec pos_shift = this->get_cam_movement (fol_cur, target, this->followedVM_vel, this->trans_tc); + // get_cam_rotation computes the rotation for the next camera position + sm::quaternion cam_rotn = this->get_cam_rotation (r_cur0, target, this->followedVM_rvel, this->rotn_tc); + + // set the translation/rotation into fol_cur + fol_cur.pretranslate (pos_shift); + fol_cur.rotate (cam_rotn); + + // Distance to rotation centre should be the distance to the followedVM + this->d_to_rotation_centre = folcam_offset_tr.length(); + + // fol_cur now contains the new position and orientation for the following camera + return fol_cur; + } + + // To zoom down to, and follow behind the agent + sm::mat update_folcam_viewmatrix() + { + if (this->followedVM == nullptr) { return sm::mat::identity(); } + // Target view from the followedVM + sm::mat rmat = sm::mat::identity(); + rmat.rotate (this->folcam_offset_rot); + // To smooth this, I need to keep a time-average of followedVM->getViewMatrix()... + sm::mat fol_targ = this->followedVM->getViewMatrix() * rmat; + fol_targ.translate (this->folcam_offset_tr); + // FIXME: I may want to update the lastSceneview matrix as fol_targ moves. + return update_viewmatrix_towards_target (fol_targ); + } + + // To zoom back to the drone view + sm::mat update_overcam_viewmatrix() + { + if (this->followedVM == nullptr) { return sm::mat::identity(); } + // fol_targ will be the inverse of the lastSceneview + constexpr sm::mat rotn_y = rotate_about_y(); + sm::mat targ = this->lastSceneview.inverse() * rotn_y; + return update_viewmatrix_towards_target (targ); + } + + // A follow-me camera view + void computeSceneview_for_follower() + { + sm::mat folcam_viewmatrix = this->update_folcam_viewmatrix(); + constexpr sm::mat rotn_y = rotate_about_y(); + this->sceneview = rotn_y * folcam_viewmatrix.inverse(); + this->savedSceneview = this->sceneview; + } + + // When we're not close to the 'overview cam' location (which is the last place you were + // before you went into viewFollowsVMBehind mode) then we need this function to get there + void computeSceneview_for_overcam() + { + sm::mat overcam_viewmatrix = this->update_overcam_viewmatrix(); // target is lastSceneview + constexpr sm::mat rotn_y = rotate_about_y(); + this->sceneview = rotn_y * overcam_viewmatrix.inverse(); + this->savedSceneview = this->sceneview; + } + + /* + * For the time t, compute the location x of a 1D minimum-jerk trajectory from 0 to xf + * carried out in time tf. + */ + template + F compute_min_jerk (const F tf, const F xf, const F t) const noexcept + { + sm::mat A = { + std::pow (tf, F{3}), F{3} * std::pow (tf, F{2}), F{6} * tf, + std::pow (tf, F{4}), F{4} * std::pow (tf, F{3}), F{2} * std::pow (tf, F{2}), + std::pow (tf, F{5}), F{5} * std::pow (tf, F{4}), F{20} * std::pow (tf, F{3}) + }; + sm::vec B = { xf, F{0}, F{0} }; + sm::vec X = A.inverse() * B; // X are the min. jerk coefficients + + F x = X[0] * t * t * t + X[1] * std::pow (t, F{4}) + X[2] * std::pow (t, F{5}); + return x; + } + + // Helper function. Is the automatic sceneview change complete after since_frames? + bool autoSceneviewComplete (const std::uint32_t since_frames) + { + return (since_frames > this->currentAutoSceneviewChange.transform_time_frames); + } + + // Choreographed sceneview changes (direction_event) + void computeSceneview_for_automation() + { + // A constexpr rotation matrix, used below + constexpr sm::mat rotn_y = rotate_about_y(); + + // We're in an 'automation mode'. use this->currentAutoSceneviewChange + std::uint32_t since_frames = this->render_counter - this->currentAutoSceneviewChange.start_frame; + + // Determine how far, in time, as a proportion, we are into the automated sceneview movement + float propn = static_cast(since_frames) / static_cast(this->currentAutoSceneviewChange.transform_time_frames); + + if (this->currentAutoSceneviewChange.event == direction_event::timed_translation) { + + if (this->autoSceneviewComplete (since_frames)) { + // Completed movement time + this->scenetrans_delta = this->currentAutoSceneviewChange.translation; + this->computeSceneview_about_rotation_centre(); + this->state.set (visual_state::viewAutomation, false); + this->scenetrans_delta.zero(); + this->savedSceneview = this->sceneview; + this->savedSceneview_tr = this->sceneview_tr; + if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } + } else { + // Translate by an increment + if (this->currentAutoSceneviewChange.min_jerk) { + propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, + static_cast(since_frames)); + } + + this->scenetrans_delta = propn * this->currentAutoSceneviewChange.translation; + this->computeSceneview_about_rotation_centre(); + } + if (this->followedVM != nullptr) { + sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; + sm::mat fvm = this->followedVM->getViewMatrix(); + this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); + } + + } else if (this->currentAutoSceneviewChange.event == direction_event::timed_rotation) { + + sm::vec mod_up = this->savedSceneview.rotation() * this->scene_up; + if (this->autoSceneviewComplete (since_frames)) { + // Apply full rotation + sm::quaternion r1 (mod_up, -this->currentAutoSceneviewChange.about_vert_angle); + sm::quaternion r2 (this->scene_right, -this->currentAutoSceneviewChange.tilt_angle); + this->rotation_delta = r2 * r1; + this->computeSceneview_about_rotation_centre(); + this->state.set (visual_state::viewAutomation, false); + this->rotation_delta.reset(); + this->savedSceneview = this->sceneview; + this->savedSceneview_tr = this->sceneview_tr; + if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } + } else { // Rotate by an increment + if (this->currentAutoSceneviewChange.min_jerk) { + propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, + static_cast(since_frames)); + } + // make rotation_delta from this->currentAutoSceneviewChange.rotation and apply + sm::quaternion r1 (mod_up, -propn * this->currentAutoSceneviewChange.about_vert_angle); + sm::quaternion r2 (this->scene_right, -propn * this->currentAutoSceneviewChange.tilt_angle); + this->rotation_delta = r2 * r1; + this->computeSceneview_about_rotation_centre(); + } + if (this->followedVM != nullptr) { + sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; + sm::mat fvm = this->followedVM->getViewMatrix(); + this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); + } + + } else if (this->currentAutoSceneviewChange.event == direction_event::timed_transform + || this->currentAutoSceneviewChange.event == direction_event::sceneview) { // translation and rotation + + if (this->autoSceneviewComplete (since_frames)) { // transform is done + this->state.set (visual_state::viewAutomation, false); + this->scenetrans_delta.zero(); + this->rotation_delta.reset(); + this->savedSceneview = this->sceneview; + this->savedSceneview_tr = this->sceneview_tr; + // Update followedLastViewMatrix now! + if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } + } else { // transform, incrementally + if (this->currentAutoSceneviewChange.min_jerk) { + // propn is time from 0 to 1 of our movement. Compute min-jerk movement x(t) + // = a3 t^3 + a4 t^4 + a5 t^5. We always pass xf = 1, as we are getting a + // proportion of the trajectory, regardless of the length (or amount of + // rotation) of our sceneview move.) + propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, + static_cast(since_frames)); + } + // Ensure propn is in range before calling slerp + if (propn > 1.0f) { propn = 1.0f; } + if (propn < 0.0f) { propn = 0.0f; } + // Translate by an increment + this->scenetrans_delta = propn * this->currentAutoSceneviewChange.translation; + // Rotate... + sm::quaternion slerped = this->currentAutoSceneviewChange.rotation_start.slerp (currentAutoSceneviewChange.rotation, propn); + { + // Here's how to check the error information in the returned quaternion. + if (slerped.w == std::numeric_limits::max()) { std::cout << __func__ << ": propn = " << propn << " was out of the range [0, 1]\n"; } + if (slerped.x == std::numeric_limits::max()) { std::cout << __func__ << ": rotation_start was not normalized\n"; } + if (slerped.y == std::numeric_limits::max()) { std::cout << __func__ << ": rotation was not normalized\n"; } + + // rather than computeSceneview_about_rotation_centre, we compute + // translation and rotation right here (this could probably be consolidated to use fewer mats) + sm::mat sv_tr = sm::mat::identity(); + sm::mat sv_rot = sm::mat::identity(); + sv_tr.translate (this->savedSceneview.translation()); + sv_tr.translate (this->scenetrans_delta); + sv_rot.rotate (slerped); + this->sceneview = sv_tr * sv_rot; + this->sceneview_tr = sv_tr; + } + } + if (this->followedVM != nullptr) { + sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; + sm::mat fvm = this->followedVM->getViewMatrix(); + this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); + } else { + this->d_to_rotation_centre = std::abs (this->sceneview[14]); + } + + } else if (this->currentAutoSceneviewChange.event == direction_event::timed_orbit) { + if (this->autoSceneviewComplete (since_frames)) { // transform is done + this->state.set (visual_state::viewAutomation, false); + this->scenetrans_delta.zero(); + this->rotation_delta.reset(); + this->savedSceneview = this->sceneview; + this->savedSceneview_tr = this->sceneview_tr; + // Update followedLastViewMatrix now! + if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } + } else { // orbit, incrementally + if (this->currentAutoSceneviewChange.min_jerk) { + propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, + static_cast(since_frames)); + } + sm::mat orb_trans = sm::mat::identity(); + orb_trans.translate (this->currentAutoSceneviewChange.orbit_centre); + sm::mat orb_trans_back = sm::mat::identity(); + orb_trans_back.translate (-this->currentAutoSceneviewChange.orbit_centre); + sm::mat orb_rot = sm::mat::identity(); + orb_rot.rotate (this->currentAutoSceneviewChange.orbit_axis, propn * this->currentAutoSceneviewChange.orbit_angle); + this->sceneview = this->savedSceneview * orb_trans * orb_rot * orb_trans_back; + } + } else { + std::cout << "Unknown direction_event\n"; + this->state.set (visual_state::viewAutomation, false); + } + } + + // This is called every time render() is called + void computeSceneview() + { + if (this->options.test (visual_options::viewFollowsVMBehind) && this->followedVM != nullptr) { + + if (this->state.test (visual_state::viewFollowsModeChanged)) { + // Record sceneview now + this->lastSceneview = this->sceneview; + this->lastSceneview_tr = this->sceneview_tr; + // THEN, we can update lastSceneview whilst also updating agent location + // then zoom back to lastSceneview as the target. + this->state.reset (visual_state::viewFollowsModeChanged); + } + + // Use scenetrans_delta to shift the view with the scrollwheel + this->folcam_offset_tr += this->scenetrans_delta; + this->scenetrans_delta.zero(); + if (this->state.test (visual_state::scrolling)) { + this->state.reset (visual_state::scrolling); + // scrolling during a view automation should cancel the view automation + this->state.reset (visual_state::viewAutomation); + } + this->computeSceneview_for_follower(); + + } else { + + // A constexpr rotation matrix, used below + constexpr sm::mat rotn_y = rotate_about_y(); + + if (this->state.test (visual_state::viewFollowsModeChanged)) { + // Changed back to normal, non-follower mode. Zoom back, so set viewTransition + this->state.set (visual_state::viewTransition); + this->state.reset (visual_state::viewFollowsModeChanged); + } + + // if sceneview is not close to lastSceneview and we have no commanded rotations + // (scenetrans_delta and rotation_delta are 0) then we make changes to return to + // lastSceneview: + if (this->state.test (visual_state::viewTransition) + && this->followedVM != nullptr + && std::abs(this->scenetrans_delta.sum()) == 0.0f + && this->rotation_delta.is_zero_rotation() == true) { + + // zoom towards lastSceneview: + this->computeSceneview_for_overcam(); + // Update d_to_rotation_centre with distance to followedVM + // scene view in world frame + sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; + // followed vm + sm::mat fvm = this->followedVM->getViewMatrix(); + + this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); + + // Did we get there? If so, set viewTransition false + if ((this->sceneview.translation() - this->lastSceneview.translation()).length() < 0.001f) { + this->state.reset (visual_state::viewTransition); + } + } else if (this->state.test (visual_state::viewAutomation)) { + + this->computeSceneview_for_automation(); + + } else { + + if (std::abs(this->scenetrans_delta.sum()) > 0.0f || this->rotation_delta.is_zero_rotation() == false) { + // Calculate model view transformation - transforming from "model space" to "worldspace". + this->computeSceneview_about_rotation_centre(); + // As we had a commanded movement, cancel the viewTransition and any viewAutomation + this->state.reset (visual_state::viewTransition); + this->state.reset (visual_state::viewAutomation); + } // else don't change sceneview + + if (this->state.test (visual_state::scrolling)) { + this->scenetrans_delta.zero(); + this->state.reset (visual_state::scrolling); + } + } + + if (this->options.test (visual_options::viewFollowsVMTranslations) + && this->followedVM != nullptr + && this->state.test (visual_state::viewAutomation) == false + && this->followedLastViewMatrix != this->followedVM->getViewMatrix()) { + + // Move camera the difference between followedLastViewMatrix and + // followedVM->getViewMatrix() in the screen frame of reference. + sm::vec fol_screenframe = (this->sceneview * followedLastViewMatrix.translation() + - this->sceneview * followedVM->getViewMatrix().translation()).less_one_dim(); + + this->sceneview.pretranslate (fol_screenframe); + this->sceneview_tr.pretranslate (fol_screenframe); + this->savedSceneview.pretranslate (fol_screenframe); + this->savedSceneview_tr.pretranslate (fol_screenframe); + this->lastSceneview.pretranslate (fol_screenframe); + this->lastSceneview_tr.pretranslate (fol_screenframe); + + this->followedLastViewMatrix = this->followedVM->getViewMatrix(); + } + } + } + + //! A vector of pointers to all the mplot::VisualModels (HexGridVisual, + //! ScatterVisual, etc) which are going to be rendered in the scene. + std::vector>> vm; + + //! If the view should follow a model (options viewFollowsVMTranslations and ...Rotations), this is the one. + mplot::VisualModel* followedVM = nullptr; + + //! Holds the current velocy of the followedVM follower + sm::vec followedVM_vel = {}; + //! Current rotational speed (how fast we slerp) + float followedVM_rvel = 0.0f; + + //! Holds the viewmatrix of the followedVM the last time we called render + sm::mat followedLastViewMatrix = sm::mat::identity(); + + //! The window (and OpenGL context) for this Visual + mplot::win_t* window = nullptr; + + //! Each window has an ID number, which is passed to the owned VisualModels + std::uint32_t visual_id = std::numeric_limits::max(); + + //! Current window width + std::int32_t window_w = 640; + //! Current window height + std::int32_t window_h = 480; + //! Window viewport scaling + float window_scale_w = 1.0f; + float window_scale_h = 1.0f; + + //! The title for the Visual. Used in window title and if saving out 3D model or png image. + std::string title = "mathplot"; + + //! The user's 'selected visual model'. For model specific changes to alpha and possibly colour + std::uint32_t selectedVisualModel = 0u; + + //! A little model of the coordinate axes. + std::unique_ptr> coordArrows; + + //! Position coordinate arrows on screen. Configurable at mplot::Visual construction. + sm::vec coordArrowsOffset = { -0.8f, -0.8f }; + + /* + * Variables to manage projection and rotation of the scene + */ + + //! Current cursor position + sm::vec cursorpos = {}; + + //! The default z position for VisualModels should be 'away from the screen' (negative) so we can see them! + constexpr static float zDefault = -5.0f; + + //! A delta scene translations + sm::vec scenetrans_delta = {}; + + //! Default for scene translation. This is a scene position that can be reverted to, to + //! 'reset the view'. This is copied into sceneview when user presses Ctrl-a. + sm::vec scenetrans_default = { 0.0f, 0.0f, zDefault }; + + //! The world depth at which text objects should be rendered + float text_z = -1.0f; + + //! Screen coordinates of the position of the last mouse press + sm::vec mousePressPosition = {}; + + //! Add additional rotation to the scene + sm::quaternion rotation_delta; + + //! The default rotation of the scene, to reconstruct the default sceneview matrix/reset rotation. + sm::quaternion rotation_default; + + //! A coordinate in the scene about which to perform a mouse-driven rotation. May be set to + //! the centre of the closest VisualModel object. + sm::vec rotation_centre = {}; + + // Distance to the 'rotation centre'. Used to scale the effect of the scroll wheel + float d_to_rotation_centre = -zDefault; + + //! The projection matrix is a member of this class. Value is set during setPerspective() or setOrthographic() + sm::mat projection = sm::mat::identity(); + + //! The inverse of the projection. Value is set during setPerspective() or setOrthographic() + sm::mat invproj = sm::mat::identity(); + + //! The sceneview matrix, which changes as the user moves the view with mouse + //! movements. Initialized in VisualOwnable constructor. + sm::mat sceneview = sm::mat::identity(); + //! The non-rotating sceneview matrix, updated only from mouse translations (avoiding rotations) + sm::mat sceneview_tr = sm::mat::identity(); + + //! Saved sceneview at mouse button down + sm::mat savedSceneview = sm::mat::identity(); + //! Saved sceneview_tr + sm::mat savedSceneview_tr = sm::mat::identity(); + + //! The sceneview when the user switched to a follow-me mode. This can become a target to return to when switching back. + sm::mat lastSceneview = sm::mat::identity(); + //! translation only version of lastSceneview + sm::mat lastSceneview_tr = sm::mat::identity(); + + // auto sceneview change. Active if visual_state::viewAutomation is set true in this->state. + mplot::direction_data currentAutoSceneviewChange; + + public: + + //! Getter for d_to_rotation_centre + float get_d_to_rotation_centre() const { return this->d_to_rotation_centre; } + + /* + * Generic callback handlers + */ + + using keyaction = mplot::keyaction; + using keymod = mplot::keymod; + using key = mplot::key; + // The key_callback handler uses GLFW codes, but they're in a mplot header (keys.h) + template + bool key_callback (std::int32_t _key, std::int32_t scancode, std::int32_t action, std::int32_t mods) // can't be virtual. + { + bool needs_render = false; + + if constexpr (owned == true) { // If Visual is 'owned' then the owning system deals with program exit + // Exit action + if (_key == key::q && (mods & keymod::control) && action == keyaction::press) { + this->signal_to_quit(); + } + } + + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::c && (mods & keymod::control) && action == keyaction::press) { + this->options.flip (visual_options::showCoordArrows); + needs_render = true; + } + + if (_key == key::h && (mods & keymod::control) && action == keyaction::press) { + // Help to stdout: + std::cout << "Ctrl-h: Output this help to stdout\n" + << "Mouse-primary: rotate mode (use Ctrl to change axis)\n" + << "Mouse-secondary: translate mode\n"; + if constexpr (owned == true) { // If Visual is 'owned' then the owning system deals with program exit + std::cout << "Ctrl-q: Request exit\n"; + } + std::cout << "Ctrl-v: Un-pause\n" + << "Ctrl-l: Toggle the scene lock\n" + << "Ctrl-c: Toggle coordinate arrows\n" + << "Ctrl-s: Take a snapshot\n" + << "Ctrl-Shift-s: Output GLSL shaders to stdout\n" + << "Ctrl-m: Save 3D models in .gltf format (open in e.g. blender)\n" + << "Ctrl-a: Reset default view\n" + << "Ctrl-o: Reduce field of view\n" + << "Ctrl-p: Increase field of view\n" + << "Ctrl-7: Decrease ambient light intensity\n" + << "Ctrl-8: Increase ambient light intensity\n" + << "Ctrl-9: Decrease diffuse light intensity\n" + << "Ctrl-0: Increase diffuse light intensity\n" + << "Ctrl-e: Sceneview matrix to stdout\n" + << "Ctrl-y: Cycle perspective\n" + << "Ctrl-k: Toggle rotate about central model or scene origin\n" + << "Ctrl-b: Toggle between 'rotate about vertical', or 'mathplot tilt'\n" + << "Ctrl-d: Switch the vertical axis used in 'rotate about vertical' mode\n" + << "Ctrl-z: Show the current scenetrans/rotation on stdout\n" + << "Ctrl-u: Reduce zNear cutoff plane\n" + << "Ctrl-i: Increase zNear cutoff plane\n" + << "Ctrl-j: Toggle bounding boxes\n" + << "Ctrl-Shift-s: Output shaders to stdout\n" + << "F1-F10: Select model index (with shift: toggle hide)\n" + << "Shift-Left: Decrease opacity of selected model\n" + << "Shift-Right: Increase opacity of selected model\n" + << std::flush; + } + + if (_key == key::l && (mods & keymod::control) && action == keyaction::press) { + this->state.flip (visual_state::sceneLocked); + std::cout << "Scene is now " << (this->state.test (visual_state::sceneLocked) ? "" : "un-") << "locked\n"; + } + + if (_key == key::e && (mods & keymod::control) && action == keyaction::press) { + constexpr sm::mat rotn_y = rotate_about_y(); + sm::mat effective_viewmatrix = this->sceneview.inverse() * rotn_y; + std::cout << this->title << " window:\n Sceneview effective camera location is " << (effective_viewmatrix * sm::vec<>{}) << std::endl; + std::cout << " Sceneview matrix array:\n" << this->sceneview.str_arr() << std::endl; + } + + if (_key == key::v && (mods & keymod::control) && action == keyaction::press) { + if (this->state.test (visual_state::paused)) { + this->state.set (visual_state::paused, false); + std::cout << "Scene un-paused\n"; + } // else no-op + } + + if (_key == key::s && (mods & (keymod::control | keymod::shift)) && action == keyaction::press) { + + if ((mods & (keymod::control | keymod::shift)) == (keymod::control | keymod::shift)) { + // Ctrl-Shift-s gives you the default shaders + std::cout << "The built-in shader programs are:\n"; + std::cout << "\nVisual.vert.glsl\n" + << "----------------\n" + << mplot::getDefaultVtxShader(glver) << std::endl; + std::cout << "\nVisual.frag.glsl\n" + << "----------------\n" + << mplot::getDefaultFragShader(glver) << std::endl; + std::cout << "\nVisText.vert.glsl\n" + << "----------------\n" + << mplot::getDefaultTextVtxShader(glver) << std::endl; + std::cout << "\nVisText.frag.glsl\n" + << "----------------\n" + << mplot::getDefaultTextFragShader(glver) << std::endl; + } else if (mods & keymod::control) { + // Ctrl-s saves a PNG + std::string fname (this->title); + mplot::tools::stripFileSuffix (fname); + fname += ".png"; + // Make fname 'filename safe' + mplot::tools::conditionAsFilename (fname); + this->saveImage (fname); + std::cout << "Saved image to '" << fname << "'\n"; + } + } + + // Save gltf 3D file + if (_key == key::m && (mods & keymod::control) && action == keyaction::press) { + std::string gltffile = this->title; + mplot::tools::stripFileSuffix (gltffile); + gltffile += ".gltf"; + mplot::tools::conditionAsFilename (gltffile); + this->savegltf (gltffile); + std::cout << "Saved 3D file '" << gltffile << "'\n"; + } + + if (_key == key::z && (mods & keymod::control) && action == keyaction::press) { + sm::quaternion rotn = this->sceneview.rotation(); + rotn.renormalize(); + sm::vec scenetrans = this->sceneview.translation(); + std::cout << "Scenetrans setup code:\n v.setSceneTrans (sm::vec{ float{" + << scenetrans.x() << "}, float{" + << scenetrans.y() << "}, float{" + << scenetrans.z() + << "} });" + << "\n v.setSceneRotation (sm::quaternion{ float{" + << rotn.w << "}, float{" << rotn.x << "}, float{" + << rotn.y << "}, float{" << rotn.z << "} });\n"; + } + + // Set selected model + if (_key == key::f1 && action == keyaction::press) { + this->selectedVisualModel = 0; + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f2 && action == keyaction::press) { + if (this->vm.size() > 1) { this->selectedVisualModel = 1; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f3 && action == keyaction::press) { + if (this->vm.size() > 2) { this->selectedVisualModel = 2; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f4 && action == keyaction::press) { + if (this->vm.size() > 3) { this->selectedVisualModel = 3; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f5 && action == keyaction::press) { + if (this->vm.size() > 4) { this->selectedVisualModel = 4; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f6 && action == keyaction::press) { + if (this->vm.size() > 5) { this->selectedVisualModel = 5; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f7 && action == keyaction::press) { + if (this->vm.size() > 6) { this->selectedVisualModel = 6; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f8 && action == keyaction::press) { + if (this->vm.size() > 7) { this->selectedVisualModel = 7; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f9 && action == keyaction::press) { + if (this->vm.size() > 8) { this->selectedVisualModel = 8; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } else if (_key == key::f10 && action == keyaction::press) { + if (this->vm.size() > 9) { this->selectedVisualModel = 9; } + std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; + } + + // Toggle hide model if the shift key is down + if ((_key == key::f10 || _key == key::f1 || _key == key::f2 || _key == key::f3 + || _key == key::f4 || _key == key::f5 || _key == key::f6 + || _key == key::f7 || _key == key::f8 || _key == key::f9) + && action == keyaction::press && (mods & keymod::shift)) { + this->vm[this->selectedVisualModel]->toggleHide(); + } + + // Increment/decrement alpha for selected model + if (_key == key::left && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::shift)) { + if (!this->vm.empty()) { this->vm[this->selectedVisualModel]->decAlpha(); } + } + if (_key == key::right && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::shift)) { + if (!this->vm.empty()) { this->vm[this->selectedVisualModel]->incAlpha(); } + } + + // Ambient and diffuse lighting intensity + if (_key == key::n9 && action == keyaction::press && (mods & keymod::control)) { + // decrease diffuse intensity + this->diffuse_intensity -= 0.05f; + if (this->diffuse_intensity <= 0.0f) { this->diffuse_intensity = 0.0f; } + std::cout << "diffuse_intensity is now " << this->diffuse_intensity << std::endl; + } else if (_key == key::n0 && action == keyaction::press && (mods & keymod::control)) { + // increase diffuse intensity + this->diffuse_intensity += 0.05f; + if (this->diffuse_intensity > 10.0f) { this->diffuse_intensity = 10.0f; } + std::cout << "diffuse_intensity is now " << this->diffuse_intensity << std::endl; + } else if (_key == key::n7 && action == keyaction::press && (mods & keymod::control)) { + // decrease ambient intensity + this->ambient_intensity -= 0.05f; + if (this->ambient_intensity <= 0.0f) { this->ambient_intensity = 0.0f; } + std::cout << "ambient_intensity is now " << this->ambient_intensity << std::endl; + } else if (_key == key::n8 && action == keyaction::press && (mods & keymod::control)) { + // increase ambient intensity + this->ambient_intensity += 0.05f; + if (this->ambient_intensity > 10.0f) { this->ambient_intensity = 10.0f; } + std::cout << "ambient_intensity is now " << this->ambient_intensity << std::endl; + } + + // Reset view to default + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::a && (mods & keymod::control) && action == keyaction::press) { + std::cout << "Reset to default view\n"; + this->sceneview.set_identity(); + this->sceneview_tr.set_identity(); + this->sceneview.translate (this->scenetrans_default); + this->sceneview.rotate (this->rotation_default); + this->sceneview_tr.translate (this->scenetrans_default); + this->scenetrans_delta.zero(); + this->rotation_delta.reset(); + this->d_to_rotation_centre = -this->scenetrans_default[2]; + //this->folcam_offset = folcam_default(); + this->folcam_offset_tr = folcam_offset_tr_default; + this->folcam_offset_rot.reset(); + needs_render = true; + } + + if (_key == key::k && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::control)) { + this->options.flip (visual_options::rotateAboutSceneOrigin); + std::cout << "Rotating about " + << (this->options.test (visual_options::rotateAboutSceneOrigin) ? "scene origin" : "central model") + << std::endl; + } + + if (_key == key::j && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::control)) { + this->options.flip (visual_options::showBoundingBoxes); + // Update all the VisualModels now: + auto vmi = this->vm.begin(); + while (vmi != this->vm.end()) { + (*vmi)->show_bb (this->options.test (visual_options::showBoundingBoxes)); + ++vmi; + } + } + + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::o && (mods & keymod::control) && action == keyaction::press) { + this->fov -= 2.0f; + if (this->fov < 1.0f) { this->fov = 2.0f; } + std::cout << "FOV reduced to " << this->fov << std::endl; + } + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::p && (mods & keymod::control) && action == keyaction::press) { + this->fov += 2.0f; + if (this->fov > 179.0f) { this->fov = 178.0f; } + std::cout << "FOV increased to " << this->fov << std::endl; + } + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::u && (mods & keymod::control) && action == keyaction::press) { + this->zNear /= 2.0f; + std::cout << "zNear reduced to " << this->zNear << std::endl; + } + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::i && (mods & keymod::control) && action == keyaction::press) { + this->zNear *= 2.0f; + std::cout << "zNear increased to " << this->zNear << std::endl; + } + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::left_bracket && (mods & keymod::control) && action == keyaction::press) { + this->zFar /= 2.0f; + std::cout << "zFar reduced to " << this->zFar << std::endl; + } + if (this->state.test (visual_state::sceneLocked) == false + && _key == key::right_bracket && (mods & keymod::control) && action == keyaction::press) { + this->zFar *= 2.0f; + std::cout << "zFar increased to " << this->zFar << std::endl; + } + + if (_key == key::y && (mods & keymod::control) && action == keyaction::press) { + if (this->ptype == mplot::perspective_type::perspective) { + this->ptype = mplot::perspective_type::orthographic; + } else if (this->ptype == mplot::perspective_type::orthographic) { + this->ptype = mplot::perspective_type::perspective; + } + needs_render = true; + } + + if (_key == key::d && (mods & keymod::control) && action == keyaction::press) { + this->switch_scene_vertical_axis(); + } + + if (_key == key::b && (mods & keymod::control) && action == keyaction::press) { + this->options.flip (visual_options::rotateAboutVertical); + if (this->options.test (visual_options::rotateAboutVertical)) { + std::cout << "Mouse rotates scene about vertical axis\n"; + } else { + std::cout << "Mouse tilts scene as in the original mathplot\n"; + } + } + + this->key_callback_extra (_key, scancode, action, mods); + + return needs_render; + } + + // Switch between 'z' up and 'y' up + void switch_scene_vertical_axis() + { + if (this->scene_up == sm::vec<>::uy()) { + std::cout << "Changing 'scene up' to uz\n"; + this->scene_up = sm::vec<>::uz(); + this->scene_right = sm::vec<>::ux(); + this->scene_out = -sm::vec<>::uy(); + } else if (this->scene_up == sm::vec<>::uz()) { + std::cout << "Changing 'scene up' to uy\n"; + this->scene_up = sm::vec<>::uy(); + this->scene_right = sm::vec<>::ux(); + this->scene_out = sm::vec<>::uz(); + } else { + std::cout << "Not changing user-specified 'scene up' from " << this->scene_up << "\n"; + } + } + + //! Rotate the scene about axis by angle (angle in radians) + void rotate_scene (const sm::vec& axis, const float angle) + { + sm::quaternion rotnQuat (axis, -angle); + this->sceneview.rotate (rotnQuat); + } + + //! Find the rotation centre; either the scene origin or the centre of a perceptually nearby VM + void find_rotation_centre() + { + // When rotating about scene origin, find translation of scene centre from screen centre + if (this->options.test (visual_options::rotateAboutSceneOrigin) == true) { + this->rotation_centre = this->savedSceneview.translation(); + return; + } + + // Otherwise, find the centre of a visual model to rotate about + constexpr sm::vec v1 = { 0.0f, 0.0f, -100.0f }; + constexpr sm::vec v2 = { 0.0f, 0.0f, 100.0f }; + constexpr sm::vec v2v1 = v1 - v2; + + // A rotation delta in world frame about the 'screen centre'. This is a default: + if (this->rotation_centre == sm::vec{}) { + this->rotation_centre = { 0.0f, 0.0f, this->savedSceneview.translation().z() + this->scenetrans_delta.z() }; + } + + // There's an option to write out the bounding box corners to a file that can be + // displayed with debug_boundingboxes.cpp + std::ofstream fout; + std::uint32_t ci = 0; + if (options.test (visual_options::boundingBoxesToJson)) { + fout.open ("/tmp/mathplot_bounding_boxes.json", std::ios::out | std::ios::trunc); + if (fout.is_open()) { fout << "{\n"; } + } + + //std::multimap, mplot::VisualModel*> > possible_centres; // tuple: didn't work with g++ + std::multimap, mplot::VisualModel*> > possible_centres; // pair + auto vmi = this->vm.begin(); + while (vmi != this->vm.end()) { + + // vm_bools comes from VisualModel and would need to be shared + if ((*vmi)->flags.test (mplot::vm_bools::compute_bb) && !(*vmi)->flags.test (mplot::vm_bools::twodimensional)) { + + sm::vec tr_bb_centre = (this->savedSceneview * (*vmi)->get_viewmatrix_bb_centre()).less_one_dim(); + + if (options.test (visual_options::boundingBoxesToJson) && fout.is_open()) { + sm::interval> modelbb = (*vmi)->bb; // Get the VisualModel bounding box + modelbb -= (*vmi)->bb.mid(); // centre the bounding box about (VM frame's) origin + modelbb += tr_bb_centre; + fout << " \"b" << (ci + 1) << "\": [" << modelbb.min.str_comma_separated() << "],\n"; + fout << " \"b" << (ci + 2) << "\": [" << modelbb.max.str_comma_separated() << "],\n"; + ci += 2; + } + + // Highlight central VM in any case. Really, want to highlight the selected possible centre. + if (options.test (visual_options::highlightRotationVM)) { (*vmi)->show_bb (false); } + + // Find perpendicular distance from line to point pc + sm::vec cv = tr_bb_centre - v1; + float pdist = cv.length() * std::sin (v2v1.angle (cv)); + + if (tr_bb_centre[2] < 0.0f) { // Only if in front of viewer (z must be negative) + // Perp. distance as key, value is tuple of BB centre and visualmodel pointer + //possible_centres.insert ({ pdist, { tr_bb_centre, (*vmi).get() } }); // tuple + possible_centres.insert ({ pdist, std::make_pair (tr_bb_centre, (*vmi).get()) }); // pair + } + } + ++vmi; + } + + if (options.test (visual_options::boundingBoxesToJson) && fout.is_open()) { + fout << " \"n\": " << ci << "\n}\n"; + fout.close(); + } + + if (!possible_centres.empty()) { + //const auto [rcentre, vmptr] = possible_centres.begin()->second; // tuple + std::pair, mplot::VisualModel*> pr = possible_centres.begin()->second; // pair + // this->rotation_centre = rcentre; // tuple + this->rotation_centre = pr.first; // pair + this->d_to_rotation_centre = this->rotation_centre.length(); + //if (options.test (visual_options::highlightRotationVM)) { vmptr->show_bb (true); } // tuple + if (options.test (visual_options::highlightRotationVM)) { pr.second->show_bb (true); } // pair + } // else don't change rotation_centre + } + + virtual bool cursor_position_callback (double x, double y) + { + this->cursorpos[0] = static_cast(x); + this->cursorpos[1] = static_cast(y); + + sm::vec mouseMoveWorld = { 0.0f, 0.0f, 0.0f }; + + bool needs_render = false; + + // Mouse-movement gain + constexpr float mm_gain = 160.0f; + + // This is "rotate the scene" (and not "rotate one VisualModel") + if (this->state.test (visual_state::rotateMode)) { + // Convert mousepress/cursor positions (in pixels) to the range -1 -> 1: + sm::vec p0_coord = this->mousePressPosition; + p0_coord -= this->window_w * 0.5f; + p0_coord /= this->window_w * 0.5f; + sm::vec p1_coord = this->cursorpos; + p1_coord -= this->window_w * 0.5f; + p1_coord /= this->window_w * 0.5f; + // Note: don't update this->mousePressPosition until user releases button. + + // Add the depth at which the object lies. Use forward projection to determine the + // correct z coordinate for the inverse projection. This assumes only one object. + sm::vec point = { 0.0f, 0.0f, this->savedSceneview.translation().z(), 1.0f }; + sm::vec pp = this->projection * point; + float coord_z = pp[2] / pp[3]; // divide by pp[3] is divide by/normalise by 'w'. + + // p0_coord/p1_coord in range -1 to 1, with a z value of 1. + sm::vec p0 = { p0_coord[0], p0_coord[1], coord_z, 1.0f }; + sm::vec p1 = { p1_coord[0], p1_coord[1], coord_z, 1.0f }; + + // Apply the inverse projection to get two points in the world frame of reference + // for the mouse movement + sm::vec v0 = this->invproj * p0; + sm::vec v1 = this->invproj * p1; + + /* + * This computes the difference between v0 and v1, the 2 mouse positions in the + * world space. Note the swap between x and y. mouseMoveWorld is used as the + * rotation axis in the viewer's frame of reference or its values are used to set + * rotations about scene axes (if rotateAboutVertical is true) + */ + if (this->state.test (visual_state::rotateModMode)) { + // Sort of "rotate the page" mode. + mouseMoveWorld[2] = (-(v1[1] - v0[1]) + (v1[0] - v0[0])); + } else { + mouseMoveWorld[1] = -(v1[0] - v0[0]); + mouseMoveWorld[0] = -(v1[1] - v0[1]); + } + mouseMoveWorld *= mm_gain; + + if (this->options.test (visual_options::rotateAboutVertical) == true + && this->options.test (visual_options::viewFollowsVMBehind) == false) { + + if (this->state.test (visual_state::rotateModMode)) { + // What to do about rotate mod mode in this rotation scheme? Rotate about the missing axis for now. + this->rotation_delta.set_rotation (this->scene_out, mouseMoveWorld[2] * -sm::mathconst::deg2rad); + } else { + // For now, rotate about the scene up axis + sm::vec<> mod_up = this->savedSceneview.rotation() * this->scene_up; + sm::quaternion r1 (mod_up, mouseMoveWorld[1] * -sm::mathconst::deg2rad); + sm::quaternion r2 (this->scene_right, mouseMoveWorld[0] * -sm::mathconst::deg2rad); + this->rotation_delta = r2 * r1; + } + } else if (this->options.test (visual_options::viewFollowsVMBehind) == true) { + //std::cout << "\nmouseMoveWorld[0]: " << mouseMoveWorld[0] << std::endl; // pitch + //std::cout << "mouseMoveWorld[1]: " << mouseMoveWorld[1] << std::endl; // about +- 40ish. leftright yaw + float pitch = mouseMoveWorld[0]; + float yaw = mouseMoveWorld[1]; + pitch = pitch > 10.0f ? 10.0f : pitch; + pitch = pitch < -65.0f ? -65.0f : pitch; // negative pitch is 'looking down' on the agent + yaw = yaw > 45.0f ? 45.0f : yaw; + yaw = yaw < -45.0f ? -45.0f : yaw; + + sm::quaternion r1 (this->scene_up, yaw * sm::mathconst::deg2rad); + sm::quaternion r2 (this->scene_right, pitch * -sm::mathconst::deg2rad); + this->folcam_offset_rot = r2 * r1; + + } else { + // rotation_delta is the mouse-commanded rotation in the scene frame of reference + this->rotation_delta.set_rotation (mouseMoveWorld, mouseMoveWorld.length() * -sm::mathconst::deg2rad); + } + + needs_render = true; + + } else if (this->state.test (visual_state::translateMode)) { // allow only rotate OR translate for a single mouse movement + // Convert mousepress/cursor positions (in pixels) to the range -1 -> 1: + sm::vec p0_coord = this->mousePressPosition; + p0_coord -= this->window_w * 0.5f; + p0_coord /= this->window_w * 0.5f; + sm::vec p1_coord = this->cursorpos; + p1_coord -= this->window_w * 0.5f; + p1_coord /= this->window_w * 0.5f; + + this->mousePressPosition = this->cursorpos; + + // Add the depth at which the object lies. Use forward projection to determine the + // correct z coordinate for the inverse projection. This assumes only one object. + sm::vec point = { 0.0f, 0.0f, -this->d_to_rotation_centre, 1.0f }; + sm::vec pp = this->projection * point; + float coord_z = pp[2] / pp[3]; // divide by pp[3] is divide by/normalise by 'w'. + + // Construct two points for the start and end of the mouse movement + sm::vec p0 = { p0_coord[0], p0_coord[1], coord_z, 1.0f }; + sm::vec p1 = { p1_coord[0], p1_coord[1], coord_z, 1.0f }; + // Apply the inverse projection to get two points in the world frame of reference: + sm::vec v0 = this->invproj * p0; + sm::vec v1 = this->invproj * p1; + // This computes the difference betwen v0 and v1, the 2 mouse positions in the world + mouseMoveWorld[0] = (v1[0] / v1[3]) - (v0[0] / v0[3]); + mouseMoveWorld[1] = (v1[1] / v1[3]) - (v0[1] / v0[3]); + // Note: mouseMoveWorld[2] is unmodified + + // We "translate the whole scene" - used by 2D projection shaders + this->scenetrans_delta[0] += mouseMoveWorld[0]; + + if (this->options.test (visual_options::viewFollowsVMBehind) == true) { + this->scenetrans_delta[1] += mouseMoveWorld[1]; // opp. sense in follow-me + } else { + this->scenetrans_delta[1] -= mouseMoveWorld[1]; + } + + needs_render = true; // updates viewproj; uses this->scenetrans + } + + return needs_render; + } + + virtual void mouse_button_callback (std::int32_t button, std::int32_t action, std::int32_t mods = 0) + { + // If the scene is locked, then ignore the mouse movements + if (this->state.test (visual_state::sceneLocked)) { return; } + + // Record the position and rotation at which the button was pressed + if (action == keyaction::press) { // Button down + this->mousePressPosition = this->cursorpos; + this->savedSceneview = this->sceneview; + this->savedSceneview_tr = this->sceneview_tr; + this->scenetrans_delta.zero(); + this->rotation_delta.reset(); + } else if (action == keyaction::release) { + // On mouse button release, zero the deltas: + this->scenetrans_delta.zero(); + this->rotation_delta.reset(); + } + + this->find_rotation_centre(); + + if (button == mplot::mousebutton::left) { // Primary button means rotate + if (action == keyaction::press) { + this->state.set (visual_state::mouseButtonLeftPressed); + } else if (action == keyaction::release) { + this->state.set (visual_state::mouseButtonLeftPressed, false); + } + this->state.set (visual_state::rotateModMode, ((mods & keymod::control) ? true : false)); + this->state.set (visual_state::rotateMode, (action == keyaction::press)); + this->state.set (visual_state::translateMode, false); + } else if (button == mplot::mousebutton::right) { // Secondary button means translate + if (action == keyaction::press) { + this->state.set (visual_state::mouseButtonRightPressed); + } else if (action == keyaction::release) { + this->state.set (visual_state::mouseButtonRightPressed, false); + } + this->state.set (visual_state::rotateMode, false); + this->state.set (visual_state::translateMode, (action == keyaction::press)); + } + + this->mouse_button_callback_extra (button, action, mods); + } + + virtual bool window_size_callback (std::int32_t width, std::int32_t height) + { + this->window_w = width; + this->window_h = height; + return true; // needs_render + } + + virtual bool window_content_scale_callback (float xscl, float yscl) + { + bool nr = false; + if (this->window_scale_w != xscl) { + this->window_scale_w = xscl; + nr = true; + } + if (this->window_scale_h != yscl) { + this->window_scale_h = yscl; + nr = true; + } + return nr; + } + + virtual void window_close_callback() + { + if (this->options.test (visual_options::preventWindowCloseWithButton) == false) { + this->signal_to_quit(); + } else { + std::cerr << "Ignoring user request to exit (Visual::preventWindowCloseWithButton)\n"; + } + } + + //! When user scrolls, we translate the scene + virtual bool scroll_callback (double xoffset, double yoffset) + { + // yoffset non-zero indicates that the most common scroll wheel is changing. If there's + // a second scroll wheel, xoffset will be passed non-zero. They'll be 0 or +/- 1. + + if (this->state.test (visual_state::sceneLocked)) { return false; } + + this->savedSceneview = this->sceneview; + this->savedSceneview_tr = this->sceneview_tr; + this->scenetrans_delta.zero(); + this->rotation_delta.reset(); + this->state.set (visual_state::scrolling); + + if (this->ptype == perspective_type::orthographic) { + // In orthographic, the wheel should scale ortho_lb and ortho_rt + sm::vec _lb = this->ortho_lb + (yoffset * this->scenetrans_stepsize); + sm::vec _rt = this->ortho_rt - (yoffset * this->scenetrans_stepsize); + if (_lb < 0.0f && _rt > 0.0f) { + this->ortho_lb = _lb; + this->ortho_rt = _rt; + } + + } else { // perspective_type::perspective + + // xoffset does what mouse drag left/right in rotateModMode does (L/R scene trans) + this->scenetrans_delta[0] -= xoffset * this->scenetrans_stepsize; + + // yoffset does the 'in-out zooming' + + // How to make scenetrans_stepsize adaptive to the scale of the environment and change when close to objects? + float y_step = static_cast(yoffset) * this->scenetrans_stepsize * this->d_to_rotation_centre; + sm::vec scroll_move_y = { 0.0f, y_step, 0.0f, 1.0f }; + + this->scenetrans_delta[2] += scroll_move_y[1]; + + if (this->d_to_rotation_centre > (this->zFar / 2.0f) && scroll_move_y[1] < 0.0f) { + // Cancel movement + this->scenetrans_delta[2] = 0.0f; + scroll_move_y[1] = 0.0f; + } + + this->d_to_rotation_centre -= this->scenetrans_delta[2]; + } + return true; // needs_render + } + + virtual void key_callback_extra ([[maybe_unused]] std::int32_t key, [[maybe_unused]] std::int32_t scancode, + [[maybe_unused]] std::int32_t action, [[maybe_unused]] std::int32_t mods) {} + + virtual void mouse_button_callback_extra ([[maybe_unused]] std::int32_t button, [[maybe_unused]] std::int32_t action, + [[maybe_unused]] std::int32_t mods) {} + + //! A callback that client code can set so that it knows when user has signalled to + //! mplot::Visual that it's quit time. + std::function external_quit_callback; + + protected: + //! This internal quit function sets a 'readyToFinish' flag that your code can respond to, + //! and calls an external callback function that you may have set up. + void signal_to_quit() + { + if (this->options.test (visual_options::userInfoStdout)) { std::cout << "User requested exit.\n"; } + // 1. Set our 'readyToFinish' flag to true + this->state.set (visual_state::readyToFinish); + // 2. Call any external callback that's been set by client code + if (this->external_quit_callback) { this->external_quit_callback(); } + } + + //! Unpause, allowing pauseOpen() to return + void unpause() { this->state.reset (visual_state::paused); } + }; + +} // namespace mplot diff --git a/mplot/VisualResources.hpp b/mplot/VisualResources.hpp new file mode 100644 index 00000000..6b7f1752 --- /dev/null +++ b/mplot/VisualResources.hpp @@ -0,0 +1,375 @@ +/*! + * \file + * + * Declares a VisualResource class to hold the information about Freetype which is a one-per-program + * resource. Also holds the Glad contexts - the OpenGL function pointers for each window. Windows + * are referred to as mplot::win_t; the identity of win_t (which might be GLFWwindow or + * QtOpenGLWidget) is abstact in this file. + * + * \author Seb James + * \date November 2020 + */ +#pragma once + +// Include GLAD header +#include + +// FreeType for text rendering +#include +#include FT_FREETYPE_H + +#include +#include +#include +#include +#include +#include + +import mplot.visualcommon; +import mplot.visualface; +import mplot.visualfont; +import mplot.textfeatures; +import mplot.win_t; +import mplot.gl.version; +import mplot.gl.util; +import sm.vec; + +namespace mplot +{ + //! Singleton resource class for mplot::Visual scenes. + template + class VisualResources + { + private: + VisualResources(){} + ~VisualResources() + { + this->faces.clear(); + // As with the case for faces, when each mplot::Visual goes out of scope, the FreeType + // instance gets cleaned up. So at this stage freetypes should also be empy and nothing + // will happen here either. + for (auto& ft : this->freetypes) { FT_Done_FreeType (ft.second); } + } + + //! The collection of VisualFaces generated for this instance of the application. Create one + //! VisualFace for each unique combination of VisualFont and fontpixels (the texture + //! resolution). uint32_t is the 'visual_id' an ID of the Visual instance. + std::map, + std::unique_ptr> faces; + + //! FreeType library object. Keyed by the 'visual_id' an ID of the Visual instance. + std::map freetypes; + + public: + VisualResources(const VisualResources&) = delete; + VisualResources& operator=(const VisualResources &) = delete; + VisualResources(VisualResources &&) = delete; + VisualResources & operator=(VisualResources &&) = delete; + + //! Initialize a freetype library instance and add to this->freetypes. I wanted + //! to have only a single freetype library instance, but this didn't work, so I + //! create one FT_Library for each OpenGL context (i.e. one for each mplot::Visual + //! window). Thus, arguably, the FT_Library should be a member of mplot::Visual, + //! but that's a task for the future, as I coded it this way under the false + //! assumption that I'd only need one FT_Library. + void freetype_init (std::uint32_t _vis, GladGLContext* glfn = nullptr) + { + FT_Library freetype = nullptr; + try { + freetype = this->freetypes.at (_vis); + } catch (const std::out_of_range&) { + // Use of gl calls here may make it neat to set up GL here in VisualResources? + glfn->PixelStorei(GL_UNPACK_ALIGNMENT, 1); // disable byte-alignment restriction + mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); + + if (FT_Init_FreeType (&freetype)) { + std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl; + } else { + // Successfully initialized freetype + this->freetypes[_vis] = freetype; + } + } + } + + //! When a mplot::Visual goes out of scope, its freetype library instance should be + //! deinitialized. + void freetype_deinit (std::uint32_t _vis) + { + // First clear the faces associated with Visual with ID _vis + this->clearVisualFaces (_vis); + // Second, clean up the FreeType library instance and erase from this->freetypes + auto freetype = this->freetypes.find (_vis); + if (freetype != this->freetypes.end()) { + FT_Done_FreeType (freetype->second); + this->freetypes.erase (freetype); + } + } + + //! The instance public function. Uses the very short name 'i' to keep code tidy. + //! This relies on C++11 magic statics (N2660). + static auto& i() + { + static VisualResources instance; + return instance; + } + + //! A function to call to simply make sure the singleton instance exists + void create() {} + + //! Return a pointer to a VisualFace for the given \a font at the given texture + //! resolution, \a fontpixels and the given window (i.e. OpenGL context) \a _win. + mplot::visgl::VisualFace* getVisualFace (mplot::VisualFont font, std::uint32_t fontpixels, + std::uint32_t _vis, GladGLContext* glfn) + { + mplot::visgl::VisualFace* rtn = nullptr; + auto key = std::make_tuple(font, fontpixels, _vis); + try { + rtn = this->faces.at(key).get(); + } catch (const std::out_of_range&) { + this->faces[key] = std::make_unique (font, fontpixels, this->freetypes.at(_vis), glfn); + rtn = this->faces.at(key).get(); + } + return rtn; + } + + mplot::visgl::VisualFace* getVisualFace (const mplot::TextFeatures& tf, + const std::uint32_t _vis, GladGLContext* glfn) + { + return this->getVisualFace (tf.font, tf.fontres, _vis, glfn); + } + + //! Loop through this->faces clearing out those associated with the given mplot::Visual + void clearVisualFaces (const std::uint32_t _vis) + { + mplot::VisualFont thefont; + std::uint32_t fpixels = 0; + std::uint32_t vf_vis = std::numeric_limits::max(); + + auto f = this->faces.begin(); + + while (f != this->faces.end()) { + // f->first is a key. If its third, visual_id element == _vis, then delete and erase + // f->first needs unpacking; want 3rd elemetn + std::tie(thefont, fpixels, vf_vis) = f->first; + + if (vf_vis == _vis) { + f = this->faces.erase (f); + } else { f++; } + } + } + + std::uint32_t next_visual_id = 0; + + // GL function context pointers used in the program, keyed by a uint32_t ID + std::map visual_keyed_gladglcontexts; + // GL shader programs used by Visual in the program, keyed by ID + std::map visual_keyed_shaderprogs; + // Window contexts + std::map visual_keyed_windows; + // Does instanced data need update? + std::map visual_keyed_instanced_needs_update; + + std::uint32_t register_visual (GladGLContext* glfn, mplot::win_t* win) + { + std::uint32_t visual_id = this->next_visual_id++; + this->visual_keyed_gladglcontexts[visual_id] = glfn; + this->visual_keyed_shaderprogs[visual_id] = {}; // initialized empty with 0s + this->visual_keyed_windows[visual_id] = win; + this->visual_keyed_instanced_needs_update[visual_id] = false; + return visual_id; + } + + // Return true if there is a GladGLContext for visual_id + bool test_glfn (const std::uint32_t visual_id) + { + if (visual_id == std::numeric_limits::max()) { + return false; + } + try { + [[maybe_unused]] GladGLContext* glfn = this->visual_keyed_gladglcontexts.at (visual_id); + return true; + } catch (const std::exception& e) {} + return false; + } + + /*! + * A VisualModel can call this method, passing in the numeric ID of the context it belongs + * to. The return value will be the correct GL context pointer. + */ + GladGLContext* get_glfn (const std::uint32_t visual_id) noexcept + { + if (visual_id == std::numeric_limits::max()) { return nullptr; } + GladGLContext* glfn = this->visual_keyed_gladglcontexts[visual_id]; + return glfn; + } + + void set_tprog (const std::uint32_t visual_id, const std::uint32_t _tprog) + { + if (visual_id == std::numeric_limits::max()) { + throw std::runtime_error ("VisualResources::set_tprog(): visual_id is unset"); + } + this->visual_keyed_shaderprogs[visual_id].tprog = _tprog; + } + + std::uint32_t get_tprog (const std::uint32_t visual_id) + { + if (visual_id == std::numeric_limits::max()) { + throw std::runtime_error ("VisualResources::get_tprog(): visual_id is unset"); + } + return this->visual_keyed_shaderprogs[visual_id].tprog; + } + + void set_gprog (const std::uint32_t visual_id, const std::uint32_t _gprog) + { + if (visual_id == std::numeric_limits::max()) { + throw std::runtime_error ("VisualResources::set_gprog(): visual_id is unset"); + } + this->visual_keyed_shaderprogs[visual_id].gprog = _gprog; + } + + std::uint32_t get_gprog (const std::uint32_t visual_id) + { + if (visual_id == std::numeric_limits::max()) { + throw std::runtime_error ("VisualResources::get_gprog(): visual_id is unset"); + } + return this->visual_keyed_shaderprogs[visual_id].gprog; + } + + /*! + * Set the window context. This has to be window-system agnostic here, so we have the + * std::function setContext_implementation that (if you are using GLFW windows) is linked at + * runtime to VisualGlfw::setContext(GLFWwindow*) + */ + void setContext (const std::uint32_t visual_id) + { + if (visual_id == std::numeric_limits::max()) { + throw std::runtime_error ("VisualResources::setContext(): visual_id is unset"); + } + if (this->setContext_implementation) { + this->setContext_implementation (this->visual_keyed_windows[visual_id]); + } + } + + //! setContext function call object + std::function setContext_implementation; + + //! Window-system agnostic releaseContext call (see also setContext) + void releaseContext() { if (this->releaseContext_implementation) { this->releaseContext_implementation(); } } + + //! releaseContext function call object + std::function releaseContext_implementation; + + bool get_instanced_needs_update (const std::uint32_t visual_id) + { + if (visual_id == std::numeric_limits::max()) { + throw std::runtime_error ("VisualResources::get_instanced_needs_update: visual_id is unset"); + } + return this->visual_keyed_instanced_needs_update[visual_id]; + } + + void instanced_needs_update (const std::uint32_t visual_id, const bool val = true) + { + if (visual_id == std::numeric_limits::max()) { + throw std::runtime_error ("VisualResources::instanced_needs_update: visual_id is unset"); + } + this->visual_keyed_instanced_needs_update[visual_id] = val; + } + + /*! + * We also manage some programm-wide SSBO objects for instanced rendering + * VisualResourcesdata in . Reserve n_to_reserve instances of data in the SSBOs. Return the + * start offset into the buffers in terms of number of instances + */ + std::uint32_t init_instance_ssbo (const std::uint32_t visual_id, const std::uint32_t n_to_reserve) + { + GladGLContext* glfn = this->get_glfn (visual_id); + std::uint32_t reservation = std::numeric_limits::max(); + if constexpr (mplot::gl::version::has_ssbo (glver) == true) { + if (this->instance_data.ready() == false) { this->instance_data.init (glfn); } + if (this->instparam_data.ready() == false) { this->instparam_data.init (glfn); } + if (n_to_reserve + this->instance_top <= this->max_instances) { + reservation = this->instance_top; + this->instance_top += n_to_reserve; + this->instance_data.resize (this->instance_top * this->floats_per_instance, 1000.0f); + this->instparam_data.resize (this->instance_top * this->floats_per_instparam); + } + } else { + throw std::runtime_error ("Instanced rendering requires OpenGL 4.3 or higher"); + } + return reservation; + } + + /*! + * Inserts the 3 values from coord into the SSBO instance buffer, starting at location + * instance_idx + */ + void insert_instance_data (const std::uint32_t instance_idx, const sm::vec& coord) + { + // If this function fails, make sure to call v.render before calling set_instance_data :) + if (instance_idx >= this->max_instances) { + throw std::runtime_error ("insert_instance_data: bad instance_idx"); + } + std::uint32_t cur_fidx = instance_idx * this->floats_per_instance; + this->instance_data.data[cur_fidx++] = coord[0]; + this->instance_data.data[cur_fidx++] = coord[1]; + this->instance_data.data[cur_fidx++] = coord[2]; + } + + /*! + * Inserts the 3 values from colour, along with alpha and scale into the SSBO instparam + * buffer, starting at location instance_idx + */ + void insert_instparam_data (const std::uint32_t instance_idx, + const std::array& colour, const float& alpha, const float& scale) + { + if (instance_idx >= this->max_instances) { + throw std::runtime_error ("insert_instparam_data: bad instance_idx"); + } + std::uint32_t cur_fidx = instance_idx * this->floats_per_instparam; + this->instparam_data.data[cur_fidx++] = colour[0]; + this->instparam_data.data[cur_fidx++] = colour[1]; + this->instparam_data.data[cur_fidx++] = colour[2]; + this->instparam_data.data[cur_fidx++] = alpha; + this->instparam_data.data[cur_fidx++] = scale; + } + + void copy_instance_ssbo_to_gpu() + { + if (this->instance_data.ready()) { this->instance_data.copy_to_gpu(); } + if (this->instparam_data.ready()) { this->instparam_data.copy_to_gpu(); } + } + + /*! + * SSBO management + */ + //! Instanced rendering mode (SSBO access). position data stored in SSBO index 1 (must match GLSL code) + static constexpr std::uint32_t instance_index = 1u; + //! colour, scale, rotation stored in SSBO index 2 + static constexpr std::uint32_t instparam_index = 2u; + //! one 3D vector is 3 floats + static constexpr std::uint32_t floats_per_instance = 3u; + //! Instance params are: colour/alpha (4 floats), scale (1 float) + static constexpr std::uint32_t floats_per_instparam = 5u; + + /*! + * This will control how much GPU RAM is allocated when using instanced rendering + * (Hopefully, when I'm finished, the RAM will be allocated only if at least one VisualModel + * is marked 'instanced'). Makes a big difference to speed of operation (unless I can send a + * portion of a buffer to the GPU). + */ + static constexpr std::uint32_t max_instances = 32u * 1024u; + static constexpr std::uint32_t max_instance_floats = floats_per_instance * max_instances; + static constexpr std::uint32_t max_instparam_floats = floats_per_instparam * max_instances; + + //! Shader Storage Buffer Object for instanced rendering - this holds positions only + mplot::gl::ssbo::instance_index, + float, mplot::VisualResources::max_instance_floats> instance_data; + //! Shader Storage Buffer Object for instanced rendering - this holds colour, alpha and scale + mplot::gl::ssbo::instparam_index, + float, mplot::VisualResources::max_instparam_floats> instparam_data; + + // The Current location from which space in the instance SSBOs should be allocated + std::uint32_t instance_top = 0; + }; + +} // namespace mplot From 0d34a1b31abdfd0443cb8acb25e757b28a80ccac Mon Sep 17 00:00:00 2001 From: Seb James Date: Sun, 29 Nov 2026 15:33:23 +0000 Subject: [PATCH 3/5] Makes a 'visual core' of the stuff that was foxing gcc. Now have different error in gcc (and helloworld compiles in clang) --- cmake/module_definitions.cmake | 92 +++--- examples/helloworld.cpp | 4 +- modules/VisualCore.cppm | 46 +++ mplot/CoordArrows.cppm | 6 +- mplot/CoordArrows.hpp | 180 +++++++++++ mplot/Visual.hpp | 308 ++++++++++++++++++ mplot/VisualDataModel.cppm | 2 +- mplot/VisualDataModel.hpp | 453 +++++++++++++++++++++++++++ mplot/VisualModel.hpp | 3 +- mplot/VisualOwnable.hpp | 9 +- mplot/VisualTextModel.hpp | 550 +++++++++++++++++++++++++++++++++ 11 files changed, 1599 insertions(+), 54 deletions(-) create mode 100644 modules/VisualCore.cppm create mode 100644 mplot/CoordArrows.hpp create mode 100644 mplot/Visual.hpp create mode 100644 mplot/VisualDataModel.hpp create mode 100644 mplot/VisualTextModel.hpp diff --git a/cmake/module_definitions.cmake b/cmake/module_definitions.cmake index 390e38cf..92e715fd 100644 --- a/cmake/module_definitions.cmake +++ b/cmake/module_definitions.cmake @@ -75,18 +75,12 @@ macro(setup_module_variables_for_mathplot base_directory maths_directory) ${base_directory}/mplot/gl/util_mx.cppm ${base_directory}/mplot/colour.cppm ${base_directory}/mplot/win_t.cppm - ${base_directory}/mplot/CoordArrows.cppm - ${base_directory}/modules/VisualOwnable.cppm - ${base_directory}/mplot/Visual.cppm ${base_directory}/mplot/VisualGlfw.cppm ${base_directory}/mplot/VisualFace.cppm ${base_directory}/mplot/TextFeatures.cppm ${base_directory}/mplot/TextGeometry.cppm - ${base_directory}/modules/VisualResources.cppm ${base_directory}/mplot/VisualCommon.cppm ${base_directory}/mplot/VisualFont.cppm - ${base_directory}/mplot/VisualTextModel.cppm - ${base_directory}/modules/VisualModel.cppm ${base_directory}/mplot/NavMesh.cppm ${base_directory}/mplot/ColourMap.cppm ${base_directory}/mplot/colourmaps_cet.cppm @@ -95,51 +89,61 @@ macro(setup_module_variables_for_mathplot base_directory maths_directory) ${base_directory}/mplot/graphing.cppm ${base_directory}/mplot/graphstyles.cppm ${base_directory}/mplot/DatasetStyle.cppm - ${base_directory}/mplot/VisualDataModel.cppm ${base_directory}/mplot/fps/profiler.cppm + + #${base_directory}/mplot/Visual.cppm + #${base_directory}/mplot/CoordArrows.cppm + #${base_directory}/mplot/VisualDataModel.cppm + #${base_directory}/mplot/VisualTextModel.cppm + #${base_directory}/modules/VisualResources.cppm + #${base_directory}/modules/VisualOwnable.cppm + #${base_directory}/modules/VisualModel.cppm + # + # These become: + ${base_directory}/modules/VisualCore.cppm ) list(REMOVE_DUPLICATES MPLOT_CORE_MODULES) # (Possibly) all the VisualModel modules. Usually, you will make # your own list of just the ones you want to compile. set(MPLOT_ALL_VISUALMODEL_MODULES - ${base_directory}/mplot/GraphVisual.cppm - ${base_directory}/mplot/GridVisual.cppm - ${base_directory}/mplot/RodVisual.cppm - ${base_directory}/mplot/RhomboVisual.cppm - ${base_directory}/mplot/VectorVisual.cppm - ${base_directory}/mplot/PlaneVisual.cppm - ${base_directory}/mplot/SphereVisual.cppm - ${base_directory}/mplot/ConeVisual.cppm - ${base_directory}/mplot/QuiverVisual.cppm - ${base_directory}/mplot/NormalsVisual.cppm - ${base_directory}/mplot/GeodesicVisual.cppm - ${base_directory}/mplot/InstancedScatterVisual.cppm - ${base_directory}/mplot/HexGridVisual.cppm - ${base_directory}/mplot/CartGridVisual.cppm - ${base_directory}/mplot/AxesVisual.cppm - ${base_directory}/mplot/TxtVisual.cppm - ${base_directory}/mplot/ScatterVisual.cppm - ${base_directory}/mplot/CurvyTellyVisual.cppm - ${base_directory}/mplot/BoolVisual.cppm - ${base_directory}/mplot/RectangleVisual.cppm - ${base_directory}/mplot/TriangleVisual.cppm - ${base_directory}/mplot/VoronoiVisual.cppm - ${base_directory}/mplot/IcosaVisual.cppm - ${base_directory}/mplot/GratingVisual.cppm - ${base_directory}/mplot/ColourBarVisual.cppm - ${base_directory}/mplot/HSVWheelVisual.cppm - ${base_directory}/mplot/CyclicColourVisual.cppm - ${base_directory}/mplot/QuadsVisual.cppm - ${base_directory}/mplot/QuadsMeshVisual.cppm - ${base_directory}/mplot/PointRowsVisual.cppm - ${base_directory}/mplot/PointRowsMeshVisual.cppm - ${base_directory}/mplot/RingVisual.cppm - ${base_directory}/mplot/SphericalProjectionVisual.cppm - ${base_directory}/mplot/HealpixVisual.cppm - ${base_directory}/mplot/PolygonVisual.cppm - ${base_directory}/mplot/TriFrameVisual.cppm - ${base_directory}/mplot/PolarVisual.cppm + # ${base_directory}/mplot/GraphVisual.cppm + # ${base_directory}/mplot/GridVisual.cppm + # ${base_directory}/mplot/RodVisual.cppm + # ${base_directory}/mplot/RhomboVisual.cppm + # ${base_directory}/mplot/VectorVisual.cppm + # ${base_directory}/mplot/PlaneVisual.cppm + # ${base_directory}/mplot/SphereVisual.cppm + # ${base_directory}/mplot/ConeVisual.cppm + # ${base_directory}/mplot/QuiverVisual.cppm + # ${base_directory}/mplot/NormalsVisual.cppm + # ${base_directory}/mplot/GeodesicVisual.cppm + # ${base_directory}/mplot/InstancedScatterVisual.cppm + # ${base_directory}/mplot/HexGridVisual.cppm + # ${base_directory}/mplot/CartGridVisual.cppm + # ${base_directory}/mplot/AxesVisual.cppm + # ${base_directory}/mplot/TxtVisual.cppm + # ${base_directory}/mplot/ScatterVisual.cppm + # ${base_directory}/mplot/CurvyTellyVisual.cppm + # ${base_directory}/mplot/BoolVisual.cppm + # ${base_directory}/mplot/RectangleVisual.cppm + # ${base_directory}/mplot/TriangleVisual.cppm + # ${base_directory}/mplot/VoronoiVisual.cppm + # ${base_directory}/mplot/IcosaVisual.cppm + # ${base_directory}/mplot/GratingVisual.cppm + # ${base_directory}/mplot/ColourBarVisual.cppm + # ${base_directory}/mplot/HSVWheelVisual.cppm + # ${base_directory}/mplot/CyclicColourVisual.cppm + # ${base_directory}/mplot/QuadsVisual.cppm + # ${base_directory}/mplot/QuadsMeshVisual.cppm + # ${base_directory}/mplot/PointRowsVisual.cppm + # ${base_directory}/mplot/PointRowsMeshVisual.cppm + # ${base_directory}/mplot/RingVisual.cppm + # ${base_directory}/mplot/SphericalProjectionVisual.cppm + # ${base_directory}/mplot/HealpixVisual.cppm + # ${base_directory}/mplot/PolygonVisual.cppm + # ${base_directory}/mplot/TriFrameVisual.cppm + # ${base_directory}/mplot/PolarVisual.cppm ) list(REMOVE_DUPLICATES MPLOT_ALL_VISUALMODEL_MODULES) diff --git a/examples/helloworld.cpp b/examples/helloworld.cpp index 55244ca5..4c56eb2a 100644 --- a/examples/helloworld.cpp +++ b/examples/helloworld.cpp @@ -1,5 +1,5 @@ -import mplot.visual; -import mplot.gl.version; +import mplot.visualcore; +//import mplot.gl.version; int main() { diff --git a/modules/VisualCore.cppm b/modules/VisualCore.cppm new file mode 100644 index 00000000..75cb8da3 --- /dev/null +++ b/modules/VisualCore.cppm @@ -0,0 +1,46 @@ +module; + +#include +#include +#include +#include +#include +#include +#include + +export module mplot.visualcore; + +// Exported by VisualOwnable +export import mplot.version; + +// Exported by VisualModel +export import mplot.gl.version; +export import mplot.colour; +export import mplot.textgeometry; +export import mplot.textfeatures; + +// Exported by VisualTextmodel +export import mplot.unicode; +export import mplot.visualface; + +export namespace mplot +{ + using mplot::visual_state; + using mplot::visual_options; + using mplot::perspective_type; + using mplot::direction_event; + using mplot::direction_data; + using mplot::VisualOwnable; + + using mplot::VisualModel; + + using mplot::VisualResources; + + using mplot::VisualTextModel; + + using mplot::VisualDataModel; + + using mplot::CoordArrows; + + using mplot::Visual; +} // namespace mplot diff --git a/mplot/CoordArrows.cppm b/mplot/CoordArrows.cppm index 2717feac..839273ec 100644 --- a/mplot/CoordArrows.cppm +++ b/mplot/CoordArrows.cppm @@ -16,10 +16,10 @@ export module mplot.coordarrows; import sm.vec; import mplot.gl.version; -export import mplot.visualmodel; -export import mplot.textfeatures; +import mplot.visualcore; +import mplot.textfeatures; import mplot.visualfont; -export import mplot.colour; +import mplot.colour; export namespace mplot { diff --git a/mplot/CoordArrows.hpp b/mplot/CoordArrows.hpp new file mode 100644 index 00000000..2c3d4f97 --- /dev/null +++ b/mplot/CoordArrows.hpp @@ -0,0 +1,180 @@ +/*! + * \file + * + * Defines a coordinate arrow class based on VisualModel + * + * \author Seb James + * \date 2019 + */ +#pragma once + +#include +#include +#include + +#include + +import sm.vec; +import mplot.gl.version; +import mplot.textfeatures; +import mplot.visualfont; +import mplot.colour; + +namespace mplot +{ + //! This class creates the vertices for a set of coordinate arrows to be rendered + //! in a 3-D scene. + template + class CoordArrows : public VisualModel + { + public: + CoordArrows() : mplot::VisualModel() {} + CoordArrows (const sm::vec& offset) : mplot::VisualModel(offset) {} + + //! Must make the boilerplate bindmodel call before calling init() (for text handling) + void init (const sm::vec _lengths, const float _thickness, const float _em) + { + this->compute_bb (false); + this->lengths = _lengths; + this->thickness = _thickness; + this->em = _em; + } + + //! You can call this AS well as the first init overload to set the axis vectors + void init (const sm::vec _x, const sm::vec _y, const sm::vec _z) + { + this->compute_bb (false); + this->x_axis = _x; + this->y_axis = _y; + this->z_axis = _z; + } + + //! Make sure coord arrow colours are ok on the given background colour. Call this *after* finalize. + void setColourForBackground (const std::array& bgcolour) + { + // For now, only worry about the centresphere: + std::array cscol = { 1.0f - bgcolour[0], 1.0f - bgcolour[1], 1.0f - bgcolour[2] }; + if (cscol != this->centresphere_col) { + this->centresphere_col = cscol; + this->reinit(); // sets context, does not release it + + // Give the text labels a suitable, visible colour + mplot::VisualResources::i().setContext (this->parentVis); + auto ti = this->texts.begin(); + while (ti != this->texts.end()) { + (*ti)->setVisibleOn (bgcolour); + ti++; + } + mplot::VisualResources::i().releaseContext(); + } + } + + void initAxisLabels() + { + if (this->em > 0.0f) { + + mplot::VisualResources::i().setContext (this->parentVis); + mplot::TextFeatures tfca(this->em, 48, false, mplot::colour::black, mplot::VisualFont::DVSansItalic); + + // These texts are black by default + sm::vec _offset = this->viewmatrix.translation(); + sm::vec toffset = {}; + toffset = _offset + this->x_axis * this->lengths[0]; + toffset[0] += this->em; + auto vtm1 = this->makeVisualTextModel (tfca); + vtm1->setupText (this->x_label, toffset); + this->texts.push_back (std::move(vtm1)); + toffset = _offset + this->y_axis * this->lengths[1]; + toffset[0] += this->em; + auto vtm2 = this->makeVisualTextModel (tfca); + vtm2->setupText (this->y_label, toffset); + this->texts.push_back (std::move(vtm2)); + toffset = _offset + this->z_axis * this->lengths[2]; + toffset[0] += this->em; + auto vtm3 = this->makeVisualTextModel (tfca); + vtm3->setupText (this->z_label, toffset); + this->texts.push_back (std::move(vtm3)); + + mplot::VisualResources::i().releaseContext(); + } + } + + //! Initialize vertex buffer objects and vertex array object. + void initializeVertices() + { + this->vertexPositions.clear(); + this->vertexNormals.clear(); + this->vertexColors.clear(); + this->indices.clear(); + this->idx = 0; + + // Draw four spheres to make up the coord frame, with centre at 0,0,0 + sm::vec reloffset = {}; + static constexpr sm::vec zerocoord = { 0.0f, 0.0f, 0.0f }; + this->computeSphere (zerocoord, centresphere_col, this->thickness * this->lengths[0] * this->centre_sphere_size); + + // x + reloffset = this->x_axis * this->lengths[0]; + this->computeSphere (reloffset, x_axis_col, this->thickness * this->lengths[0] * this->endsphere_size); + this->computeTube (zerocoord, reloffset, x_axis_col, x_axis_col, this->thickness * this->lengths[0] * this->tube_size); + if (showneg) { + this->computeTube (zerocoord, -reloffset, x_axis_neg, x_axis_neg, this->thickness * this->lengths[0] * this->tube_size); + } + + // y + reloffset = this->y_axis * this->lengths[1]; + this->computeSphere (reloffset, y_axis_col, this->thickness * this->lengths[0] * this->endsphere_size); + this->computeTube (zerocoord, reloffset, y_axis_col, y_axis_col, this->thickness * this->lengths[0] * this->tube_size); + if (showneg) { + this->computeTube (zerocoord, -reloffset, y_axis_neg, y_axis_neg, this->thickness * this->lengths[0] * this->tube_size); + } + + // z + reloffset = this->z_axis * this->lengths[2]; + this->computeSphere (reloffset, z_axis_col, this->thickness * this->lengths[0] * this->endsphere_size); + this->computeTube (zerocoord, reloffset, z_axis_col, z_axis_col, this->thickness * this->lengths[0] * this->tube_size); + if (showneg) { + this->computeTube (zerocoord, -reloffset, z_axis_neg, z_axis_neg, this->thickness * this->lengths[0] * this->tube_size); + } + + this->initAxisLabels(); + } + + //! The lengths of the coordinate arrows + sm::vec lengths = { 1.0f, 1.0f, 1.0f }; + + //! The axes for the coordinate arrows. A simple right handed coordinate system aligned with + //! the 'real' world coordinate system by default. + sm::vec x_axis = sm::vec::ux(); + sm::vec y_axis = sm::vec::uy(); + sm::vec z_axis = sm::vec::uz(); + + //! A thickness scaling factor, to scale all thicknesses at once + float thickness = 1.0f; + //! The radius of the end spheres as a proportion of the length + float endsphere_size = 1.0f / 40.0f; + //! The radius of the centre sphere as a proportion of the length + float centre_sphere_size = 1.0f / 20.0f; + //! The radius of the arrows, as a proportion of the length + float tube_size = 1.0f / 80.0f; + //! m size for text labels + float em = 0.0f; + + //! The colours of the arrows, and of the centre sphere (where default of black is suitable + //! for a white background) + std::array centresphere_col = mplot::colour::black; + std::array x_axis_col = mplot::colour::crimson; + std::array y_axis_col = mplot::colour::springgreen2; + std::array z_axis_col = mplot::colour::blue2; + + bool showneg = false; + std::array x_axis_neg = mplot::colour::raspberry; + std::array y_axis_neg = mplot::colour::darkseagreen3; + std::array z_axis_neg = mplot::colour::steelblue3; + + std::string x_label = "X"; + std::string y_label = "Y"; + std::string z_label = "Z"; + }; + +} // namespace mplot diff --git a/mplot/Visual.hpp b/mplot/Visual.hpp new file mode 100644 index 00000000..c2787216 --- /dev/null +++ b/mplot/Visual.hpp @@ -0,0 +1,308 @@ +/*! + * \file + * + * Awesome graphics code for high performance graphing and visualisation. + * + * This is the main visual scene class in mathplot and derives from mplot::VisualOwnable, adding + * window handling with GLFW3. + * + * This is the multiple context-safe version of VisualNoMX. + * + * It is further aliased to mplot::Visual in mplot/Visual.h. + * + * Created by Seb James on 2025/03/03 + * + * \author Seb James + * \date May 2025 + */ +#pragma once + +#ifndef _glfw3_h_ // glfw3 has not yet been externally included +# define GLFW_INCLUDE_NONE // Here, we tell GLFW that we will explicitly include GL3/gl3.h and GL/glext.h +# include +#endif // _glfw3_h_ + +#include +#include +#include +#include + +#include +#include + +import mplot.gl.version; +import mplot.win_t; + +import mplot.visualglfw; + +namespace mplot +{ + /*! + * Visual 'scene' class + * + * A class for visualising computational models on an OpenGL screen. + * + * Each Visual will have its own GLFW window and is essentially a "scene" containing a number + * of objects. One object might be the visualisation of some data expressed over a + * HexGrid. Another could be a GraphVisual object. The class handles mouse events to allow the + * user to rotate and translate the scene, as well as use keys to generate particular + * effects/views. + * + * It's possible to set the background colour of the scene (Visual::bgcolour), the location of + * the objects in the scene (Visual::setSceneTransZ and friends) and the position and field of + * view of the 'camera' (Visual::zNear, Visual::zFar and Visual::fov). + * + * \tparam glver The OpenGL version, encoded as a single int (see mplot::gl::version) + */ + template + class Visual : public mplot::VisualOwnable + { + public: + /*! + * Construct a new visualiser. The rule is 1 window to one Visual object. So, this creates a + * new window and a new OpenGL context. + */ + Visual (const std::int32_t _width, const std::int32_t _height, const std::string& _title, const bool _version_stdout = true) + { + this->window_w = _width; + this->window_h = _height; + this->title = _title; + this->options.set (visual_options::versionStdout, _version_stdout); + + this->init_resources(); + this->init_gl(); // could this come before init_resources? NO, because init_gl has + // VisualTextModel stuff that requires init_resources. Could maybe split init_gl + } + + //! Deconstructor destroys GLFW/Qt window and deregisters access to VisualResources + ~Visual() + { + this->setContext(); + glfwDestroyWindow (this->window); + this->deconstructCommon(); + } + + // Do one-time init of the Visual's resources. This gets/creates the VisualResources, + // registers this visual with resources, calls init_window for any glfw stuff that needs to + // happen, and lastly initializes the freetype code. + void init_resources() + { + mplot::VisualGlfw::i().init(); // Init GLFW windows system + // VisualResources provides font management. Ensure it exists in memory. + mplot::VisualResources::i().create(); + // Connect the static set/releaseContext calls from VisualGlfw to the VisualResources calls + mplot::VisualResources::i().setContext_implementation = mplot::VisualGlfw::setContext; + mplot::VisualResources::i().releaseContext_implementation = mplot::VisualGlfw::releaseContext; + // Set up the window that will present the OpenGL graphics. This has to + // happen BEFORE the call to VisualResources::freetype_init() + this->init_window(); + // Check: when is this->shaders set up? in *init_gl*! So need a set_shaders method in VisualResouces + this->visual_id = mplot::VisualResources::i().register_visual (this->glfn, this->window); + this->setContext(); // For freetype_init + mplot::VisualResources::i().freetype_init (this->visual_id, this->glfn); + this->releaseContext(); + } + + void setSwapInterval() final + { + // Swap as fast as possible (fixes lag of scene with mouse movements) + glfwSwapInterval (0); + } + + //! Make this Visual the current one, so that when creating/adding a visual model, the vao + //! ids relate to the correct OpenGL context. + void setContext() final { glfwMakeContextCurrent (this->window); } + + //! swapBuffers implementation for glfw + void swapBuffers() final { glfwSwapBuffers (this->window); } + + //! Lock the context to prevent accessing the OpenGL context from multiple threads + //! then obtain the context. + void lockContext() + { + this->context_mutex.lock(); + this->setContext(); + } + + //! Attempt to lock the context. If the mutex lock is obtained, set the OpenGL + //! context and return true. If the mutex lock is not obtained, return false. + bool tryLockContext() + { + if (this->context_mutex.try_lock()) { + this->setContext(); + return true; + } + return false; + } + + //! Release the OpenGL context and unlock the context mutex. + void unlockContext() + { + this->releaseContext(); + this->context_mutex.unlock(); + } + + //! Release the OpenGL context + void releaseContext() final { glfwMakeContextCurrent (nullptr); } + + /*! + * \brief OpenGL context check + * + * You can see if the OpenGL context is held at any time in your program. This function + * returns true if there is a non-null window and we currently 'have that context'. This + * should return true after a call to Visual::setContext and false after a call to + * Visual::releaseContext. + */ + bool checkContext() + { + return this->window == nullptr ? false : (glfwGetCurrentContext() == this->window); + } + + //! Obtain the window pointer + win_t* getWindow() { return this->window; } + + /* + * A note on setContext() in keepOpen/poll/waitevents/wait: + * + * I considered automatically calling setContext in these functions. However, the event + * queue is not necessarily bound to the context (it depends on the platform), so I will + * leave these as they are. The call to render() inside keepOpen() WILL correctly induce a + * setContext() call. + */ + + /*! + * Keep on rendering until readToFinish is set true. Used to keep a window open, and + * responsive, while displaying the result of a simulation. FIXME: This won't work for two + * or more windows because it will block. + */ + void keepOpen() + { + while (this->state.test (visual_state::readyToFinish) == false) { + glfwWaitEventsTimeout (0.01667); // 16.67 ms ~ 60 Hz + this->render(); + } + } + + /*! + * Like keepOpen, but renders until paused is set false (or user signals they're ready to + * finish), then returns. + */ + void pauseOpen() + { + this->state.set (visual_state::paused); + while (this->state.test (visual_state::paused) == true && this->state.test (visual_state::readyToFinish) == false) { + glfwWaitEventsTimeout (0.01667); // 16.67 ms ~ 60 Hz + this->render(); + } + } + + //! Wrapper around the glfw polling function + void poll() { glfwPollEvents(); } + //! A wait-for-events with a timeout wrapper + void waitevents (const double& timeout) { glfwWaitEventsTimeout (timeout); } + //! Collect events for timeout, returning after *all* the time elapsed + void wait (const double& timeout) + { + using sc = std::chrono::steady_clock; + sc::time_point t0 = sc::now(); + sc::time_point t1 = sc::now(); + std::int32_t timeout_us = timeout * 1000000; + while (std::chrono::duration_cast(t1 - t0).count() < timeout_us) { + glfwWaitEventsTimeout (timeout/10.0); + t1 = sc::now(); + } + } + + private: + + void init_window() + { + this->window = glfwCreateWindow (this->window_w, this->window_h, this->title.c_str(), NULL, NULL); + if (!this->window) { + // Window or OpenGL context creation failed + throw std::runtime_error("GLFW window creation failed!"); + } + // now associate "this" object with mWindow object + glfwSetWindowUserPointer (this->window, this); + + // Set up callbacks + glfwSetKeyCallback (this->window, key_callback_dispatch); + glfwSetMouseButtonCallback (this->window, mouse_button_callback_dispatch); + glfwSetCursorPosCallback (this->window, cursor_position_callback_dispatch); + glfwSetWindowSizeCallback (this->window, window_size_callback_dispatch); + glfwSetWindowContentScaleCallback (this->window, window_content_scale_callback_dispatch); + glfwSetWindowCloseCallback (this->window, window_close_callback_dispatch); + glfwSetScrollCallback (this->window, scroll_callback_dispatch); + + glfwMakeContextCurrent (this->window); + glfwGetWindowContentScale (this->window, &this->window_scale_w, &this->window_scale_h); + + this->init_glad (glfwGetProcAddress); + } + + private: + //! Context mutex to prevent contexts being acquired in a non-threadsafe manner. + std::mutex context_mutex; + + /* + * GLFW callback dispatch functions + */ + static void key_callback_dispatch (GLFWwindow* _window, std::int32_t key, std::int32_t scancode, std::int32_t action, std::int32_t mods) + { + Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); + if (self->key_callback (key, scancode, action, mods)) { + self->render(); + } + } + static void mouse_button_callback_dispatch (GLFWwindow* _window, std::int32_t button, std::int32_t action, std::int32_t mods) + { + Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); + self->mouse_button_callback (button, action, mods); + } + static void cursor_position_callback_dispatch (GLFWwindow* _window, double x, double y) + { + Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); + if (self->cursor_position_callback (x, y)) { + self->render(); + } + } + static void window_size_callback_dispatch (GLFWwindow* _window, std::int32_t width, std::int32_t height) + { + Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); + if (self->window_size_callback (width, height)) { + self->render(); + } + } + static void window_content_scale_callback_dispatch (GLFWwindow* _window, float xscl, float yscl) + { + Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); + if (self->window_content_scale_callback (xscl, yscl)) { + self->render(); + } + } + static void window_close_callback_dispatch (GLFWwindow* _window) + { + Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); + self->window_close_callback(); + } + static void scroll_callback_dispatch (GLFWwindow* _window, double xoffset, double yoffset) + { + Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); + if (self->scroll_callback (xoffset, yoffset)) { + self->render(); + } + } + + + public: + + /* + * Generic callback handlers + */ + virtual bool key_callback (std::int32_t _key, std::int32_t scancode, std::int32_t action, std::int32_t mods) + { + return mplot::VisualOwnable::template key_callback (_key, scancode, action, mods); + } + }; + +} // namespace mplot diff --git a/mplot/VisualDataModel.cppm b/mplot/VisualDataModel.cppm index 1055c4c4..49246ec9 100644 --- a/mplot/VisualDataModel.cppm +++ b/mplot/VisualDataModel.cppm @@ -14,7 +14,7 @@ export import sm.vvec; export import sm.scale; import sm.centroid; -export import mplot.visualmodel; +export import mplot.visualcore; export import mplot.colourmap; export import mplot.gl.version; diff --git a/mplot/VisualDataModel.hpp b/mplot/VisualDataModel.hpp new file mode 100644 index 00000000..bc7d5983 --- /dev/null +++ b/mplot/VisualDataModel.hpp @@ -0,0 +1,453 @@ +/*! + * VisualModels which have data. + */ +#pragma once + +#include +#include +#include + +#include + +import sm.vec; +import sm.vvec; +import sm.scale; +import sm.centroid; + +import mplot.colourmap; +import mplot.gl.version; + +namespace mplot +{ + // How should a VisualDataModel visualize complex data? + enum class complex_number_handling : std::uint32_t + { + as_real_scalar, + as_imaginary_scalar, + as_magnitude_scalar, + as_phase_scalar, + // many ways to do this. magnitude = z, phase = colour; colour from real/imag colour from mag/phase + as_colour_phase_magnitude_z, // two scalars + as_colour_vector_real_imaginary, + as_colour_vector_magnitude_phase + }; + + //! VisualDataModel implementation base class containing common functionality - all the + //! sm::scale objects and methods. + template + struct VisualDataModel_impl_base : public VisualModel + { + VisualDataModel_impl_base() : mplot::VisualModel::VisualModel() {} + VisualDataModel_impl_base (const sm::vec _offset) : mplot::VisualModel::VisualModel (_offset) {} + //! Deconstructor should *not* deallocate data - client code should do that + ~VisualDataModel_impl_base() {} + + //! Reset the autoscaled flags so that the next time data is transformed by + //! the Scale objects they will autoscale again (assuming they have + //! do_autoscale set true). + void clearAutoscale() + { + if (this->zScale.do_autoscale == true) { this->zScale.reset(); } + if (this->colourScale.do_autoscale == true) { this->colourScale.reset(); } + if (this->colourScale2.do_autoscale == true) { this->colourScale2.reset(); } + if (this->colourScale3.do_autoscale == true) { this->colourScale3.reset(); } + if (this->vectorScale.do_autoscale == true) { this->vectorScale.reset(); } + } + + void clearAutoscaleZ() { if (this->zScale.do_autoscale == true) { this->zScale.reset(); } } + void clearAutoscaleColour() + { + if (this->colourScale.do_autoscale == true) { this->colourScale.reset(); } + if (this->colourScale2.do_autoscale == true) { this->colourScale2.reset(); } + if (this->colourScale3.do_autoscale == true) { this->colourScale3.reset(); } + } + void clearAutoscaleVector() { if (this->vectorScale.do_autoscale == true) { this->vectorScale.reset(); } } + + void setZScale (const sm::scale& zscale) { this->zScale = zscale; } + void setCScale (const sm::scale& cscale) { this->colourScale = cscale; } + + void updateZScale (const sm::scale& zscale) + { + this->zScale = zscale; + this->reinit(); + } + + void updateCScale (const sm::scale& cscale) + { + this->colourScale = cscale; + this->reinit(); + } + + void setVectorScale (const sm::scale>& vscale) + { + this->vectorScale = vscale; + this->reinit(); + } + + void setColourMap (ColourMapType _cmt, const float _hue = 0.0f) + { + this->cm.setHue (_hue); + this->cm.setType (_cmt); + } + + //! An overridable function to set the colour of rect ri + std::array setColour (std::uint64_t ri) + { + std::array clr = { 0.0f, 0.0f, 0.0f }; + if (this->cm.numDatums() == 3) { + if constexpr (std::is_integral>::value) { + // Differs from above as we divide by 255 to get value in range 0-1 + clr = this->cm.convert (this->dcolour[ri]/255.0f, this->dcolour2[ri]/255.0f, this->dcolour3[ri]/255.0f); + } else { + clr = this->cm.convert (this->dcolour[ri], this->dcolour2[ri], this->dcolour3[ri]); + } + } else if (this->cm.numDatums() == 2) { + // Use vectorData + clr = this->cm.convert (this->dcolour[ri], this->dcolour2[ri]); + } else { + clr = this->cm.convert (this->dcolour[ri]); + } + return clr; + } + + //! All data models use a a colour map. Change the type/hue of this colour map + //! object to generate different types of map. + ColourMap cm; + + //! A Scaling function for the colour map. Perhaps a scale class contains a + //! colour map? If not, then this scale might well be autoscaled. Applied to scalarData. + sm::scale colourScale; + //! Scale for second colour (when used with vectorData). This is used if the ColourMap cm is + //! ColourMapType::DuoChrome of ColourMapType::HSV. + sm::scale colourScale2; + //! scale for third colour (when used with vectorData). Use if ColourMap cm is + //! ColourMapType::TriChrome. + sm::scale colourScale3; + + //! A scale to scale (or autoscale) scalarData. This might be used to set z + //! locations of data coordinates based on scalarData. The scaling may + sm::scale zScale; + + //! A scaling function for the vectorData. This will scale the lengths of the + //! vectorData. + sm::scale> vectorScale; + + //! If visualizing vector of complex, how to treat/visualize the data? + mplot::complex_number_handling complexHandling = mplot::complex_number_handling::as_real_scalar; + + /* + * Scaled data. Used in GridVisual classes and PolarVisual or anywhere else where scalarData + * or vectorData are scaled to be z values or colours. + */ + + //! A copy of the scalarData which can be transformed suitably to be the z value of the surface + sm::vvec dcopy; + //! A copy of the scalarData (or first field of vectorData), scaled to be a colour value + sm::vvec dcolour; + //! For the second field of vectorData + sm::vvec dcolour2; + //! For the third field of vectorData + sm::vvec dcolour3; + + //! The length of the data structure that will be visualized. May be length of + //! this->scalarData or of this->vectorData. + std::uint32_t datasize = 0; + }; + + //! VisualDataModel implementation that deals with std::vector pointers to scalar/vector data + template + struct VisualDataModel_impl : public VisualDataModel_impl_base + { + void setScalarData (const std::vector* _data) { this->scalarData = _data; } + void setVectorData (const std::vector>* _vectors) { this->vectorData = _vectors; } + void setDataCoords (std::vector>* _coords) { this->dataCoords = _coords; } + void setComplexData (const std::vector>* _data) { this->complexData = _data; } + + //! Update the scalar data + virtual void updateData (const std::vector* _data) + { + this->scalarData = _data; + this->reinit(); + } + + //! Update the scalar data with an associated z-scaling + void updateData (const std::vector* _data, const sm::scale& zscale) + { + this->scalarData = _data; + this->zScale = zscale; + this->reinit(); + } + + //! Update the scalar data, along with both the z-scaling and the colour-scaling + void updateData (const std::vector* _data, const sm::scale& zscale, const sm::scale& cscale) + { + this->scalarData = _data; + this->zScale = zscale; + this->colourScale = cscale; + this->reinit(); + } + + virtual void updateData (const std::vector>* _data) + { + this->complexData = _data; + this->reinit(); + } + + + //! Update coordinate data and scalar data along with z-scaling for scalar data + virtual void updateData (std::vector>* _coords, const std::vector* _data, + const sm::scale& zscale) + { + this->dataCoords = _coords; + this->scalarData = _data; + this->zScale = zscale; + this->reinit(); + } + + //! Update coordinate data and scalar data along with z- and colour-scaling for scalar data + virtual void updateData (std::vector>* _coords, const std::vector* _data, + const sm::scale& zscale, const sm::scale& cscale) + { + this->dataCoords = _coords; + this->scalarData = _data; + this->zScale = zscale; + this->colourScale = cscale; + this->reinit(); + } + + //! Update just the coordinate data + virtual void updateCoords (std::vector>* _coords) + { + this->dataCoords = _coords; + this->reinit(); + } + + //! Update the vector data (for plotting quiver plots) + void updateData (const std::vector>* _vectors) + { + this->vectorData = _vectors; + this->reinit(); + } + + //! Update both coordinate and vector data + void updateData (std::vector>* _coords, const std::vector>* _vectors) + { + this->dataCoords = _coords; + this->vectorData = _vectors; + this->reinit(); + } + + //! Find datasize + void determine_datasize() + { + this->datasize = 0; + if (this->vectorData != nullptr && !this->vectorData->empty()) { + this->datasize = this->vectorData->size(); + } else if (this->scalarData != nullptr && !this->scalarData->empty()) { + this->datasize = this->scalarData->size(); + } else if (this->complexData != nullptr && !this->complexData->empty()) { + this->datasize = this->complexData->size(); + } // else datasize remains 0 + } + + // Common function for setting up the z and colour scaling + void setupScaling() + { + this->dcopy.resize (this->datasize, 0.0f); + this->dcolour.resize (this->datasize); + + if (this->scalarData != nullptr) { + // What do these scaling operations do to any NaNs in scalarData? They should remain + // NaN. Then in dcopy, might want to make them 0. + this->zScale.transform (*(this->scalarData), this->dcopy); + this->dcopy.replace_nan_with (this->zScale.transform_one(0.0f)); + this->colourScale.transform (*(this->scalarData), this->dcolour); + + } else if (this->complexData != nullptr) { + if (this->complexHandling == mplot::complex_number_handling::as_colour_vector_real_imaginary + || this->complexHandling == mplot::complex_number_handling::as_colour_vector_magnitude_phase) { + + // No need to worry about scaling colourScale here, as dcolour/dcolour2 are autoscaled later. + + this->dcolour2.resize (this->datasize); + this->dcolour3.resize (this->datasize); // though we won't use this + sm::vvec veclens(this->dcopy); + if (this->complexHandling == mplot::complex_number_handling::as_colour_vector_real_imaginary) { + for (std::uint32_t i = 0; i < this->datasize; ++i) { + veclens[i] = std::abs((*this->complexData)[i]); + this->dcolour[i] = std::real ((*this->complexData)[i]); + this->dcolour2[i] = std::imag ((*this->complexData)[i]); + } + } else { + for (std::uint32_t i = 0; i < this->datasize; ++i) { + veclens[i] = std::abs((*this->complexData)[i]); + this->dcolour[i] = std::abs ((*this->complexData)[i]); + this->dcolour2[i] = std::arg ((*this->complexData)[i]); + } + } + this->zScale.transform (veclens, this->dcopy); + + } else if (this->complexHandling == mplot::complex_number_handling::as_colour_phase_magnitude_z) { + + // As we call transform_one, we have to first loop through and 'manually + // autoscale' if scaling was not already set by the client code. + if (this->zScale.ready() == false || this->colourScale.ready() == false) { + auto inrange = sm::interval::search_initialized(); + auto col_inrange = sm::interval::search_initialized(); + for (std::uint32_t i = 0; i < this->datasize; ++i) { + inrange.update (std::abs ((*this->complexData)[i])); + col_inrange.update (std::arg ((*this->complexData)[i])); + } + if (this->zScale.ready() == false) { + this->zScale.compute_scaling (inrange); + } + if (this->colourScale.ready() == false) { + this->colourScale.compute_scaling (col_inrange); + } + } + + for (std::uint32_t i = 0; i < this->datasize; ++i) { + this->dcopy[i] = this->zScale.transform_one (std::abs ((*this->complexData)[i])); + if (std::isnan(this->dcopy[i])) { this->dcopy[i] = this->zScale.transform_one(0.0f); } + this->dcolour[i] = this->colourScale.transform_one (std::arg ((*this->complexData)[i])); + } + } else { + + // As we call transform_one, we have to first loop through and 'manually + // autoscale' if scaling was not already set by the client code. + if (this->zScale.ready() == false || this->colourScale.ready() == false) { + auto inrange = sm::interval::search_initialized(); + for (std::uint32_t i = 0; i < this->datasize; ++i) { + if (this->complexHandling == mplot::complex_number_handling::as_real_scalar) { + inrange.update (std::real ((*this->complexData)[i])); + } else if (this->complexHandling == mplot::complex_number_handling::as_imaginary_scalar) { + inrange.update (std::imag ((*this->complexData)[i])); + } else if (this->complexHandling == mplot::complex_number_handling::as_magnitude_scalar) { + inrange.update (std::abs ((*this->complexData)[i])); + } else if (this->complexHandling == mplot::complex_number_handling::as_phase_scalar) { + inrange.update (std::arg ((*this->complexData)[i])); + } // do nothing + } + if (this->colourScale.ready() == false) { + this->colourScale.compute_scaling (inrange); + } + if (this->zScale.ready() == false) { + this->zScale.compute_scaling (inrange); + } + } + + for (std::uint32_t i = 0; i < this->datasize; ++i) { + T _in = T{0}; + if (this->complexHandling == mplot::complex_number_handling::as_real_scalar) { + _in = std::real ((*this->complexData)[i]); + } else if (this->complexHandling == mplot::complex_number_handling::as_imaginary_scalar) { + _in = std::imag ((*this->complexData)[i]); + } else if (this->complexHandling == mplot::complex_number_handling::as_magnitude_scalar) { + _in = std::abs ((*this->complexData)[i]); + } else if (this->complexHandling == mplot::complex_number_handling::as_phase_scalar) { + _in = std::arg ((*this->complexData)[i]); + } else { + throw std::runtime_error ("VisualDataModel: Unhandled complex_number_handling type"); + } + this->dcopy[i] = this->zScale.transform_one (_in); + if (std::isnan(this->dcopy[i])) { this->dcopy[i] = this->zScale.transform_one(0.0f); } + this->dcolour[i] = this->colourScale.transform_one (_in); + } + } + + } else if (this->vectorData != nullptr) { + + this->dcolour2.resize (this->datasize); + this->dcolour3.resize (this->datasize); + sm::vvec veclens(this->dcopy); + for (std::uint32_t i = 0; i < this->datasize; ++i) { + veclens[i] = (*this->vectorData)[i].length(); + this->dcolour[i] = (*this->vectorData)[i][0]; + this->dcolour2[i] = (*this->vectorData)[i][1]; + // Could also extract a third colour for Trichrome vs Duochrome (or for raw RGB signal) + this->dcolour3[i] = (*this->vectorData)[i][2]; + } + this->zScale.transform (veclens, this->dcopy); + } + + if (this->vectorData != nullptr + || (this->complexData != nullptr + && (this->complexHandling == mplot::complex_number_handling::as_colour_vector_real_imaginary + || this->complexHandling == mplot::complex_number_handling::as_colour_vector_magnitude_phase))) { + // Handle case where this->cm.getType() == mplot::ColourMapType::RGB and there is + // exactly one colour. ColourMapType::RGB (and RGBMono/Grey) assumes R/G/B data all + // in range 0->1 ALREADY and therefore they don't need to be re-scaled with + // this->colourScale. + if (this->cm.getType() != mplot::ColourMapType::RGB + && this->cm.getType() != mplot::ColourMapType::RGBMono + && this->cm.getType() != mplot::ColourMapType::RGBGrey) { + this->colourScale.transform (this->dcolour, this->dcolour); + // Dual axis colour maps like Duochrome and HSV will need to use colourScale2 to + // transform their second colour/axis, + this->colourScale2.transform (this->dcolour2, this->dcolour2); + // Similarly for Triple axis maps + this->colourScale3.transform (this->dcolour3, this->dcolour3); + } // else assume dcolour/dcolour2/dcolour3 are all in range 0->1 (or 0-255) already + } + } + + sm::vec coordsCentroid() const { return sm::algo::centroid (*this->dataCoords); } + + /*! + * Scalar data to visualize. T may simply be float or double. + */ + const std::vector* scalarData = nullptr; + + /*! + * Complex valued data to visualize. One may wish to: + * + * * treat complex as if it were scalar, and use just the real component + * * treat complex as if it were scalar and use just the imaginary component + * * treat complex as if it were scalar and use the magnitude + * * treat complex as if it were scalar and use the phase + * * treat complex as a 2D vector and visulize in several possible ways + */ + const std::vector>* complexData = nullptr; + + /*! + * Vector data to visualize (possibly as colour info, possibly as quiver direction) + */ + const std::vector>* vectorData = nullptr; + + /*! + * The coordinates at which to visualize data, if appropriate (e.g. scatter graph, quiver + * plot). Note fixed type of float, which is suitable for OpenGL coordinates. Not const as + * child code may resize or update content. + */ + std::vector>* dataCoords = nullptr; + }; + +#if 0 // We could add another implementation here, in which the data are provided as std::span + + //! VisualDataModel implementation that deals with std::spans to scalar/vector data + template + struct VisualDataModel_impl<1, T, glver> : public VisualDataModel_impl_base + { + // span functions + void setScalarData (std::span _data) { this->scalarData = _data; } + // ...etc + + // span attributes instead of the std::vector<>* + std::span scalarData; + std::span> vectorData; + std::span> dataCoords; + }; +#endif + + /*! + * VisualDataModel is an optional 'data layer' for VisualModels. It is used in several of the + * built-in VisualModels such as HexGridVisual, GridVisual and ScatterVisual. It provides a way + * to refer to the data (such as using std::vector<> pointers) and all the scaling functions + * that are useful for turning the data into colours and positions in the scene. It is not + * necessary to use VisualDataModel as your base class; you can derive directly from VisualModel + * (for an example see InstancedScatterVisual) + */ + template + struct VisualDataModel : public VisualDataModel_impl<0, T, glver> {}; + +} // namespace mplot diff --git a/mplot/VisualModel.hpp b/mplot/VisualModel.hpp index 9d1e8119..e3c17b8c 100644 --- a/mplot/VisualModel.hpp +++ b/mplot/VisualModel.hpp @@ -35,6 +35,7 @@ #include #include +#include import sm.mathconst; import sm.geometry; @@ -52,7 +53,7 @@ import sm.base64; import mplot.gl.version; import mplot.visualcommon; //import mplot.visualresources; -import mplot.visualtextmodel; +//import mplot.visualtextmodel; import mplot.colour; import mplot.gl.util; import mplot.tools; diff --git a/mplot/VisualOwnable.hpp b/mplot/VisualOwnable.hpp index 02f1fa70..4d517d5b 100644 --- a/mplot/VisualOwnable.hpp +++ b/mplot/VisualOwnable.hpp @@ -37,15 +37,18 @@ #include #include +#include +#include +#include import mplot.version; -import mplot.visualmodel; // make header +//import mplot.visualmodel; // make header import mplot.win_t; import mplot.visualcommon; -import mplot.visualtextmodel; +//import mplot.visualtextmodel; import mplot.textgeometry; import mplot.textfeatures; -import mplot.coordarrows; +//import mplot.coordarrows; import mplot.gl.version; import mplot.gl.util; import mplot.tools; diff --git a/mplot/VisualTextModel.hpp b/mplot/VisualTextModel.hpp new file mode 100644 index 00000000..ee0722c4 --- /dev/null +++ b/mplot/VisualTextModel.hpp @@ -0,0 +1,550 @@ +/*! + * \file + * + * Declares a class to hold vertices of the quads that are the backing for a sequence of text + * characters. This is for use in VisualModel-derived classes. Within the backend, the + * VisualTextModel classes are used directly. + * + * \author Seb James + * \date Oct 2020 - Mar 2026 + */ +#pragma once + +#if defined __gl3_h_ || defined __gl_h_ +// GL headers have been externally included +#else +# include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include + +import mplot.visualcommon; +import mplot.textgeometry; +import mplot.textfeatures; +import mplot.unicode; +import mplot.visualface; +import mplot.colour; +import mplot.gl.version; +import mplot.gl.util; + +import sm.mathconst; +import sm.quaternion; +import sm.mat; +import sm.vec; + +namespace mplot +{ + /*! + * This is the base class for VisualTextModel containing common code, but no GL function calls. + */ + template + struct VisualTextModel + { + public: + VisualTextModel (mplot::TextFeatures _tf) + { + this->tf = _tf; + this->fontscale = tf.fontsize / static_cast(tf.fontres); + } + + ~VisualTextModel() + { + if (this->vbos != nullptr) { + // To be a visualresources get + GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + _glfn->DeleteBuffers (this->numVBO, this->vbos.get()); + _glfn->DeleteVertexArrays (1, &this->vao); + } + } + + //! Render the VisualTextModel + void render() + { + if (this->hide == true) { return; } + + std::int32_t prev_shader; + std::uint32_t tshaderprog = mplot::VisualResources::i().get_tprog (this->parentVis); + GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + + _glfn->GetIntegerv (GL_CURRENT_PROGRAM, &prev_shader); + + // Ensure the correct program is in play for this VisualModel + _glfn->UseProgram (tshaderprog); + + // Set uniforms + std::int32_t loc_tc = _glfn->GetUniformLocation (tshaderprog, static_cast("textColor")); + if (loc_tc != -1) { _glfn->Uniform3f (loc_tc, this->clr_text[0], this->clr_text[1], this->clr_text[2]); } + std::int32_t loc_a = _glfn->GetUniformLocation (tshaderprog, static_cast("alpha")); + if (loc_a != -1) { _glfn->Uniform1f (loc_a, this->alpha); } + std::int32_t loc_v = _glfn->GetUniformLocation (tshaderprog, static_cast("v_matrix")); + if (loc_v != -1) { _glfn->UniformMatrix4fv (loc_v, 1, GL_FALSE, this->scenematrix.arr.data()); } + std::int32_t loc_m = _glfn->GetUniformLocation (tshaderprog, static_cast("m_matrix")); + if (loc_m != -1) { _glfn->UniformMatrix4fv (loc_m, 1, GL_FALSE, this->viewmatrix.arr.data()); } + + _glfn->ActiveTexture (GL_TEXTURE0); + + // It is only necessary to bind the vertex array object before rendering + _glfn->BindVertexArray (this->vao); + + // We have a max of (2^32)-1 characters. Should be enough. + for (std::uint32_t i = 0U; i < this->quads.size(); ++i) { + // Bind the right texture for the quad. + _glfn->BindTexture (GL_TEXTURE_2D, this->quad_ids[i]); + // This is 'draw a subset of the elements from the vertex array + // object'. You say how many indices to draw and which base *vertex* you + // start from. In my scheme, I have 4 vertices for each two triangles + // that are constructed. Thus, I draw 6 indices, but increment the base + // vertex by 4 for each letter. + _glfn->DrawElementsBaseVertex (GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, 4*i); + } + + _glfn->BindVertexArray(0); + _glfn->UseProgram (prev_shader); + + mplot::gl::Util::checkError (__FILE__, __LINE__, _glfn); + } + + //! Compute the geometry for a sample text. + mplot::TextGeometry getTextGeometry (const std::string& _txt) + { + mplot::TextGeometry geom; + + if (!mplot::VisualResources::i().test_glfn (this->parentVis)) { return geom; } + if (this->face == nullptr) { + GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + this->face = VisualResources::i().getVisualFace (this->tf, this->parentVis, _glfn); + } + + // First convert string from ASCII/UTF-8 into Unicode. + std::basic_string utxt = mplot::unicode::fromUtf8(_txt); + // on g++ 15 there's an issue with operator!= when used in a module + for (std::basic_string::const_iterator c = utxt.cbegin(); c != utxt.cend(); c++) { + mplot::visgl::CharInfo ci = this->face->glchars[*c]; + float drop = (ci.size.y() - ci.bearing.y()) * this->fontscale; + geom.max_drop = (drop > geom.max_drop) ? drop : geom.max_drop; + float bearingy = ci.bearing.y() * this->fontscale; + geom.max_bearingy = (bearingy > geom.max_bearingy) ? bearingy : geom.max_bearingy; + geom.total_advance += ((ci.advance>>6)*this->fontscale); + } + return geom; + } + + //! Return the geometry for the stored txt + mplot::TextGeometry getTextGeometry() + { + mplot::TextGeometry geom; + + if (!mplot::VisualResources::i().test_glfn (this->parentVis)) { return geom; } + if (this->face == nullptr) { + GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + this->face = VisualResources::i().getVisualFace (this->tf, this->parentVis, _glfn); + } + + for (std::basic_string::const_iterator c = this->txt.begin(); c != this->txt.end(); c++) { + mplot::visgl::CharInfo ci = this->face->glchars[*c]; + float drop = (ci.size.y() - ci.bearing.y()) * this->fontscale; + geom.max_drop = (drop > geom.max_drop) ? drop : geom.max_drop; + float bearingy = ci.bearing.y() * this->fontscale; + geom.max_bearingy = (bearingy > geom.max_bearingy) ? bearingy : geom.max_bearingy; + geom.total_advance += ((ci.advance>>6)*this->fontscale); + } + return geom; + } + + //! Set up a new text at a given position, with the given colour. + void setupText (const std::string& _txt, + const sm::vec _offset, std::array _clr = {0,0,0}) + { + this->viewmatrix.translate (_offset); + this->clr_text = _clr; + this->setupText (_txt); + } + + //! Set up a new text at a given position, with the given colour and a pre-rotation + void setupText (const std::string& _txt, + const sm::quaternion& _rotation, const sm::vec _offset, + std::array _clr = {0,0,0}) + { + this->viewmatrix.translate (_offset); + this->viewmatrix.rotate (_rotation); + this->clr_text = _clr; + this->setupText (_txt); + } + + void setupText (const std::string& _txt) + { + // Convert std::string _txt to std::basic_string text and call the other setupText + this->setupText (mplot::unicode::fromUtf8 (_txt)); + } + + //! With the given text and font size information, create the quads for the text. + void setupText (const std::basic_string& _txt) + { + constexpr bool debug_textquads = false; + + if (this->face == nullptr) { + GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + this->face = VisualResources::i().getVisualFace (this->tf, this->parentVis, _glfn); + } + + this->txt = _txt; + // With glyph information from txt, set up this->quads. + this->quads.clear(); + this->quad_ids.clear(); + // Our string of letters starts at this location + float letter_pos = 0.0f; + float letter_y = 0.0f; + float text_epsilon = 0.0f; + for (std::basic_string::const_iterator c = this->txt.begin(); c != this->txt.end(); c++) { + + if (*c == '\n') { + // Skip newline, but add a y offset and reset letter_pos + letter_pos = 0.0f; + mplot::visgl::CharInfo ch = this->face->glchars['h']; + letter_y += this->line_spacing * -ch.size.y() * this->fontscale; + continue; + } + + // Add a quad to this->quads + mplot::visgl::CharInfo ci = this->face->glchars[*c]; + + float xpos = letter_pos + ci.bearing.x() * this->fontscale; + float ypos = letter_y - (ci.size.y() - ci.bearing.y()) * this->fontscale; + float w = ci.size.x() * this->fontscale; + float h = ci.size.y() * this->fontscale; + + // Update extents + if (xpos < this->extents[0]) { this->extents[0] = xpos; } // left + if (xpos+w > this->extents[1]) { this->extents[1] = xpos+w; } // right + if (ypos < this->extents[2]) { this->extents[2] = ypos; } // bottom + if (ypos+h > this->extents[3]) { this->extents[3] = ypos+h; } // top + + // What's the order of the vertices for the quads? It is: + // Bottom left, Top left, top right, bottom right. + std::array tbox = { xpos, ypos, text_epsilon, + xpos, ypos+h, text_epsilon, + xpos+w, ypos+h, text_epsilon, + xpos+w, ypos, text_epsilon }; + text_epsilon -= 10.0f * std::numeric_limits::epsilon(); + if constexpr (debug_textquads == true) { + std::cout << "Text box added as quad from\n(" + << tbox[0] << "," << tbox[1] << "," << tbox[2] + << ") to (" << tbox[3] << "," << tbox[4] << "," << tbox[5] + << ") to (" << tbox[6] << "," << tbox[7] << "," << tbox[8] + << ") to (" << tbox[9] << "," << tbox[10] << "," << tbox[11] + << "). w="<quads.push_back (tbox); + this->quad_ids.push_back (ci.textureID); + + // The value in ci.advance has to be divided by 64 to bring it into the + // same units as the ci.size and ci.bearing values. + letter_pos += ((ci.advance>>6)*this->fontscale); + } + + // Ensure we've cleared out vertex info + this->vertexPositions.clear(); + this->vertexNormals.clear(); + this->vertexColors.clear(); + this->vertexTextures.clear(); + this->indices.clear(); + + this->initializeVertices(); + + this->postVertexInit(); + } + + protected: + + //! Common code to call after the vertices have been set up. + void postVertexInit() + { + GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + if (this->vbos == nullptr) { + // Create vertex array object + _glfn->GenVertexArrays (1, &this->vao); // Safe for OpenGL 4.4- + } + + _glfn->BindVertexArray (this->vao); + + if (this->vbos == nullptr) { + // Create the vertex buffer objects + this->vbos = std::make_unique(this->numVBO); + _glfn->GenBuffers (this->numVBO, this->vbos.get()); // OpenGL 4.4- safe + } + + // Set up the indices buffer - bind and buffer the data in this->indices + _glfn->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]); + + //std::cout << "indices.size(): " << this->indices.size() << std::endl; + std::size_t sz = this->indices.size() * sizeof(std::uint32_t); + _glfn->BufferData(GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW); + + // Binds data from the "C++ world" to the OpenGL shader world for + // "position", "normalin" and "color" + // (bind, buffer and set vertex array object attribute) + this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc); + this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc); + this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc); + this->setupVBO (this->vbos[this->textureVBO], this->vertexTextures, visgl::textureLoc); + + // Possibly release (unbind) the vertex buffers, but have to unbind vertex + // array object first. + _glfn->BindVertexArray(0); // carefully unbind + } + + //! A face for this text. The face is specfied by tf.font + mplot::visgl::VisualFace* face = nullptr; + + //! Set up a vertex buffer object - bind, buffer and set vertex array object attribute + void setupVBO (std::uint32_t& buf, std::vector& dat, std::uint32_t bufferAttribPosition) + { + std::size_t sz = dat.size() * sizeof(float); + GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); + _glfn->BindBuffer (GL_ARRAY_BUFFER, buf); + _glfn->BufferData (GL_ARRAY_BUFFER, sz, dat.data(), GL_STATIC_DRAW); + _glfn->VertexAttribPointer (bufferAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, (void*)(0)); + _glfn->EnableVertexAttribArray (bufferAttribPosition); + } + + public: + //! Set clr_text to a value suitable to be visible on the background colour bgcolour + void setVisibleOn (const std::array& bgcolour) + { + constexpr float factor = 0.85f; + this->clr_text = {1.0f - bgcolour[0] * factor, 1.0f - bgcolour[1] * factor, 1.0f - bgcolour[2] * factor}; + } + + //! Setter for VisualTextModel::viewmatrix, the model view + void setViewMatrix (const sm::mat& mv) { this->viewmatrix = mv; } + + //! Setter for VisualTextModel::scenematrix, the scene view + void setSceneMatrix (const sm::mat& sv) { this->scenematrix = sv; } + + //! Set the translation specified by \a v0 into the scene translation + template requires (N == 3) || (N == 4) + void setSceneTranslation (const sm::vec& v0) + { + this->scenematrix.set_identity(); + this->scenematrix.translate (v0); + } + + //! Set a translation (only) into the scene view matrix + template requires (N == 3) || (N == 4) + void addSceneTranslation (const sm::vec& v0) { this->scenematrix.pretranslate (v0); } + + //! Set a rotation (only) into the scene view matrix + void setSceneRotation (const sm::quaternion& r) + { + auto _offset = this->scenematrix.translation(); + this->scenematrix.set_identity(); + this->scenematrix.translate (_offset); + this->scenematrix.rotate (r); + } + + //! Add a rotation to the scene view matrix + void addSceneRotation (const sm::quaternion& r) { this->scenematrix.rotate (r); } + + //! Set a translation to the model view matrix + template requires (N == 3) || (N == 4) + void setViewTranslation (const sm::vec& v0) + { + this->viewmatrix.set_identity(); + this->viewmatrix.translate (v0); + } + + //! Add a translation to the model view matrix + void addViewTranslation (const sm::vec& v0) { this->viewmatrix.pretranslate (v0); } + + //! Set a rotation (only) into the model view matrix + void setViewRotation (const sm::quaternion& r) + { + auto tr = this->viewmatrix.translation(); + this->viewmatrix.set_identity(); + this->viewmatrix.translate (tr); + this->viewmatrix.rotate (r); + } + + //! Apply a further rotation to the model view matrix + void addViewRotation (const sm::quaternion& r) { this->viewmatrix.rotate (r); } + + + float width() const { return this->extents[1] - this->extents[0]; } + float height() const { return this->extents[3] - this->extents[2]; } + + std::string getText() const + { + std::string s = {}; + for (auto c : txt) { s += unicode::toUtf8 (c); } + return s; + } + + std::string debugText() const { return this->getText(); } + + protected: + + //! Initialize the vertices that will represent the Quads. + void initializeVertices() { + + constexpr bool debug_textquads = false; + + std::uint32_t nquads = static_cast(this->quads.size()); + + for (std::uint32_t qi = 0; qi < nquads; ++qi) { + + std::array quad = this->quads[qi]; + + if constexpr (debug_textquads == true) { + std::cout << "Quad box from (" << quad[0] << "," << quad[1] << "," << quad[2] + << ") to (" << quad[3] << "," << quad[4] << "," << quad[5] + << ") to (" << quad[6] << "," << quad[7] << "," << quad[8] + << ") to (" << quad[9] << "," << quad[10] << "," << quad[11] << ")" << std::endl; + } + + this->vertex_push (quad[0], quad[1], quad[2], this->vertexPositions); //1 + this->vertex_push (quad[3], quad[4], quad[5], this->vertexPositions); //2 + this->vertex_push (quad[6], quad[7], quad[8], this->vertexPositions); //3 + this->vertex_push (quad[9], quad[10], quad[11], this->vertexPositions); //4 + + // Add the info for drawing the textures on the quads + this->vertex_push (0.0f, 1.0f, 0.0f, this->vertexTextures); + this->vertex_push (0.0f, 0.0f, 0.0f, this->vertexTextures); + this->vertex_push (1.0f, 0.0f, 0.0f, this->vertexTextures); + this->vertex_push (1.0f, 1.0f, 0.0f, this->vertexTextures); + + // All same colours + this->vertex_push (this->clr_backing, this->vertexColors); + this->vertex_push (this->clr_backing, this->vertexColors); + this->vertex_push (this->clr_backing, this->vertexColors); + this->vertex_push (this->clr_backing, this->vertexColors); + + // All same normals + this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); + this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); + this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); + this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); + + // Two triangles per quad + // qi * 4 + 1, 2 3 or 4 + std::uint32_t ib = static_cast(qi) * 4u; + this->indices.push_back (ib++); // 0 + this->indices.push_back (ib++); // 1 + this->indices.push_back (ib); // 2 + + this->indices.push_back (ib++); // 2 + this->indices.push_back (ib); // 3 + ib -= 3; + this->indices.push_back (ib); // 0 + } + } + + public: + // A VisualTextModel may be given a name + std::string name = "VisualTextModel"; + + //! The colour of the text + std::array clr_text = {0.0f, 0.0f, 0.0f}; + //! Line spacing, in multiples of the height of an 'h' + float line_spacing = 1.4f; + //! Parent Visual. The mplot::Visual ID to which I belong. max means unset. + std::uint32_t parentVis = std::numeric_limits::max(); + + //! Setter for the parent pointer, parentVis + void set_parent (const std::uint32_t _vis) + { + if (this->parentVis != std::numeric_limits::max()) { + throw std::runtime_error ("VisualTextModel: Set the parent pointer once only!"); + } + this->parentVis = _vis; + } + + protected: + // The text features for this VisualTextModel + mplot::TextFeatures tf; + + // face is in derived class + + //! The colour of the backing quad's vertices. Doesn't have any effect. + std::array clr_backing = {1.0f, 1.0f, 0.0f}; + + //! A scaling factor based on the desired width of an 'm' + float fontscale = 1.0f; // fontscale = tf.fontsize/(float)tf.fontres; + + //! A rotation of the parent model + sm::quaternion parent_rotation = {}; + + //! The text-model-specific view matrix and a scene matrix + sm::mat viewmatrix = sm::mat::identity(); + //! Before, I wrote: We protect the scene matrix as updating it with the parent + //! model's scene matrix likely involves also adding an additional + //! translation. Now, I'm still slightly confused as to whether I *need* to have a + //! copy of the scenematrix *here*. + sm::mat scenematrix = sm::mat::identity(); + + //! The text string stored for debugging + std::basic_string txt; + //! The Quads that form the 'medium' for the text textures. 12 float = 4 corners + std::vector> quads = {}; + //! left, right, top and bottom extents of the text for this + //! VisualTextModel. setupText should modify these as it sets up quads. Order of + //! numbers is left, right, bottom, top + sm::vec extents = { 1e7, -1e7, 1e7, -1e7 }; + //! The texture ID for each quad - so that we draw the right texture image over each quad. + std::vector quad_ids = {}; + //! Position within vertex buffer object (if I use an array of VBO) + enum VBOPos { posnVBO, normVBO, colVBO, idxVBO, textureVBO, numVBO }; + //! The OpenGL Vertex Array Object + std::uint32_t vao = 0; + //! Single vbo to use as in example + std::uint32_t vbo = 0; + //! Vertex Buffer Objects stored in an array + std::unique_ptr vbos; + //! CPU-side data for indices + std::vector indices = {}; + //! CPU-side data for quad vertex positions + std::vector vertexPositions = {}; + //! CPU-side data for quad vertex normals + std::vector vertexNormals = {}; + //! CPU-side data for vertex colours + std::vector vertexColors = {}; + //! data for textures + std::vector vertexTextures = {}; + //! A model-wide alpha value for the shader + float alpha = 1.0f; + //! If true, then calls to VisualModel::render should return + bool hide = false; + + //! Push three floats onto the vector of floats \a vp + void vertex_push (const float& x, const float& y, const float& z, std::vector& vp) + { + vp.emplace_back (x); + vp.emplace_back (y); + vp.emplace_back (z); + } + //! Push array of 3 floats onto the vector of floats \a vp + void vertex_push (const std::array& arr, std::vector& vp) + { + vp.emplace_back (arr[0]); + vp.emplace_back (arr[1]); + vp.emplace_back (arr[2]); + } + //! Push mplot::vec of 3 floats onto the vector of floats \a vp + template requires (N == 3 || N == 4) + void vertex_push (const sm::vec& vec, std::vector& vp) + { + vp.emplace_back (vec[0]); + vp.emplace_back (vec[1]); + vp.emplace_back (vec[2]); + } + }; + +} // namespace mplot From 4fb96c70db3b7c796211c067e6afb35f39ff3d5a Mon Sep 17 00:00:00 2001 From: Seb James Date: Sun, 29 Nov 2026 15:53:12 +0000 Subject: [PATCH 4/5] Enables the hexgrid example, by adding HexGridvisual --- cmake/module_definitions.cmake | 2 +- examples/hexgrid.cpp | 3 +-- mplot/HexGridVisual.cppm | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cmake/module_definitions.cmake b/cmake/module_definitions.cmake index 92e715fd..211c01bc 100644 --- a/cmake/module_definitions.cmake +++ b/cmake/module_definitions.cmake @@ -119,7 +119,7 @@ macro(setup_module_variables_for_mathplot base_directory maths_directory) # ${base_directory}/mplot/NormalsVisual.cppm # ${base_directory}/mplot/GeodesicVisual.cppm # ${base_directory}/mplot/InstancedScatterVisual.cppm - # ${base_directory}/mplot/HexGridVisual.cppm + ${base_directory}/mplot/HexGridVisual.cppm # ${base_directory}/mplot/CartGridVisual.cppm # ${base_directory}/mplot/AxesVisual.cppm # ${base_directory}/mplot/TxtVisual.cppm diff --git a/examples/hexgrid.cpp b/examples/hexgrid.cpp index 0809c443..edeb66c9 100644 --- a/examples/hexgrid.cpp +++ b/examples/hexgrid.cpp @@ -24,8 +24,7 @@ import sm.vec; import sm.hexgrid; import sm.algo.hexgrid; // hexgrid algorithms, particularly the ability to reduce down to the 'next-coarser' grid -import mplot.visual; -import mplot.visualdatamodel; +import mplot.visualcore; import mplot.hexgridvisual; // We make some dummy data (a sine wave) to show on our hexgrids and either colour or elevation diff --git a/mplot/HexGridVisual.cppm b/mplot/HexGridVisual.cppm index 7f9ec553..c2b58efc 100644 --- a/mplot/HexGridVisual.cppm +++ b/mplot/HexGridVisual.cppm @@ -17,7 +17,7 @@ import sm.scale; export import mplot.gl.version; export import mplot.colourmap; import mplot.tools; -export import mplot.visualdatamodel; +export import mplot.visualcore; export namespace mplot { From 89ba93b8cde716f950bd885d461161c5719865ac Mon Sep 17 00:00:00 2001 From: Seb James Date: Sun, 29 Nov 2026 16:19:27 +0000 Subject: [PATCH 5/5] Makes a core set of headers that compile into a 'VisualCore' - mplot.visualcore. Same error compiling in gcc! --- cmake/module_definitions.cmake | 3 +- examples/helloworld.cpp | 3 +- examples/hexgrid.cpp | 2 +- modules/Visual.cppm | 20 + modules/VisualCore.cppm | 13 +- modules/VisualModel.cppm | 24 - modules/VisualOwnable.cppm | 33 - modules/VisualResources.cppm | 18 - mplot/CMakeLists.txt | 8 +- mplot/CoordArrows.cppm | 181 -- mplot/HexGridVisual.cppm | 2 +- mplot/Visual.cppm | 309 --- mplot/Visual.hpp | 7 +- mplot/VisualDataModel.cppm | 454 ---- mplot/VisualModel.cppm | 3949 -------------------------------- mplot/VisualOwnable.cppm | 2497 -------------------- mplot/VisualResources.cppm | 377 --- mplot/VisualTextModel.cppm | 551 ----- 18 files changed, 40 insertions(+), 8411 deletions(-) create mode 100644 modules/Visual.cppm delete mode 100644 modules/VisualModel.cppm delete mode 100644 modules/VisualOwnable.cppm delete mode 100644 modules/VisualResources.cppm delete mode 100644 mplot/CoordArrows.cppm delete mode 100644 mplot/Visual.cppm delete mode 100644 mplot/VisualDataModel.cppm delete mode 100644 mplot/VisualModel.cppm delete mode 100644 mplot/VisualOwnable.cppm delete mode 100644 mplot/VisualResources.cppm delete mode 100644 mplot/VisualTextModel.cppm diff --git a/cmake/module_definitions.cmake b/cmake/module_definitions.cmake index 211c01bc..dc4f3979 100644 --- a/cmake/module_definitions.cmake +++ b/cmake/module_definitions.cmake @@ -91,7 +91,8 @@ macro(setup_module_variables_for_mathplot base_directory maths_directory) ${base_directory}/mplot/DatasetStyle.cppm ${base_directory}/mplot/fps/profiler.cppm - #${base_directory}/mplot/Visual.cppm + ${base_directory}/modules/Visual.cppm + #${base_directory}/mplot/CoordArrows.cppm #${base_directory}/mplot/VisualDataModel.cppm #${base_directory}/mplot/VisualTextModel.cppm diff --git a/examples/helloworld.cpp b/examples/helloworld.cpp index 4c56eb2a..9b69715c 100644 --- a/examples/helloworld.cpp +++ b/examples/helloworld.cpp @@ -1,5 +1,4 @@ -import mplot.visualcore; -//import mplot.gl.version; +import mplot.visual; int main() { diff --git a/examples/hexgrid.cpp b/examples/hexgrid.cpp index edeb66c9..ef054c8d 100644 --- a/examples/hexgrid.cpp +++ b/examples/hexgrid.cpp @@ -24,7 +24,7 @@ import sm.vec; import sm.hexgrid; import sm.algo.hexgrid; // hexgrid algorithms, particularly the ability to reduce down to the 'next-coarser' grid -import mplot.visualcore; +import mplot.visual; import mplot.hexgridvisual; // We make some dummy data (a sine wave) to show on our hexgrids and either colour or elevation diff --git a/modules/Visual.cppm b/modules/Visual.cppm new file mode 100644 index 00000000..ca00df66 --- /dev/null +++ b/modules/Visual.cppm @@ -0,0 +1,20 @@ +/*! + * \file + * + * cppm wrapper + * + * \author Seb James + * \date Nov 2026 + */ +module; + +#include + +export module mplot.visual; + +export import mplot.visualcore; + +export namespace mplot +{ + using mplot::Visual; +} diff --git a/modules/VisualCore.cppm b/modules/VisualCore.cppm index 75cb8da3..bc0d9c79 100644 --- a/modules/VisualCore.cppm +++ b/modules/VisualCore.cppm @@ -1,25 +1,26 @@ module; +#include #include #include #include #include #include #include -#include +//#include export module mplot.visualcore; -// Exported by VisualOwnable +// Originally exported by VisualOwnable export import mplot.version; -// Exported by VisualModel +// Originally exported by VisualModel export import mplot.gl.version; export import mplot.colour; export import mplot.textgeometry; export import mplot.textfeatures; -// Exported by VisualTextmodel +// Originally exported by VisualTextmodel export import mplot.unicode; export import mplot.visualface; @@ -42,5 +43,5 @@ export namespace mplot using mplot::CoordArrows; - using mplot::Visual; -} // namespace mplot +// using mplot::Visual; +} diff --git a/modules/VisualModel.cppm b/modules/VisualModel.cppm deleted file mode 100644 index 7316f683..00000000 --- a/modules/VisualModel.cppm +++ /dev/null @@ -1,24 +0,0 @@ -/*! - * \file - * - * cppm wrapper - * - * \author Seb James - * \date Nov 2026 - */ -module; - -#include - -export module mplot.visualmodel; - -export import mplot.gl.version; -export import mplot.textfeatures; -export import mplot.textgeometry; -export import mplot.colour; -export import mplot.visualresources; - -export namespace mplot -{ - using mplot::VisualModel; -} diff --git a/modules/VisualOwnable.cppm b/modules/VisualOwnable.cppm deleted file mode 100644 index 754e9bb4..00000000 --- a/modules/VisualOwnable.cppm +++ /dev/null @@ -1,33 +0,0 @@ -/*! - * \file - * - * Awesome graphics code for high performance graphing and visualisation. - * - * This is intermediate class that sets up (multicontext aware) GL, leaving choice of window system - * (GLFW3/Qt/wx/etc) to a derived class such as mplot::Visual or mplot::qt::viswidget. - * - * This class is 'ownable', and can be used in other window drawing system such as Qt and wx, as - * well as within mplot::Visual, which marries it with the GLFW3 windowing system. - * - * Created by Seb James on 2026/11/29, as a wrapper around a header. - * - * \author Seb James - * \date March 2025 - */ -module; - -#include - -export module mplot.visualownable; - -export import mplot.version; - -export namespace mplot -{ - using mplot::visual_state; - using mplot::visual_options; - using mplot::perspective_type; - using mplot::direction_event; - using mplot::direction_data; - using mplot::VisualOwnable; -} // namespace mplot diff --git a/modules/VisualResources.cppm b/modules/VisualResources.cppm deleted file mode 100644 index 39f8342b..00000000 --- a/modules/VisualResources.cppm +++ /dev/null @@ -1,18 +0,0 @@ -/*! - * \file - * - * cppm wrapper for VisualResources.hpp - * - * \author Seb James - * \date November 2026 - */ -module; - -#include - -export module mplot.visualresources; - -export namespace mplot -{ - using mplot::VisualResources; -} diff --git a/mplot/CMakeLists.txt b/mplot/CMakeLists.txt index 9c78e992..bb39f145 100644 --- a/mplot/CMakeLists.txt +++ b/mplot/CMakeLists.txt @@ -17,7 +17,7 @@ install( colourmaps_cet.cppm colourmaps_crameri.cppm ConeVisual.cppm - CoordArrows.cppm + CoordArrows.hpp CurvyTellyVisual.cppm CyclicColourVisual.cppm DatasetStyle.cppm @@ -68,8 +68,8 @@ install( version.cppm VerticesVisual.cppm VisualCommon.cppm - Visual.cppm - VisualDataModel.cppm + Visual.hpp + VisualDataModel.hpp VisualDefaultShaders.hpp VisualFaceAsm.cpp VisualFaceAsm.hpp @@ -79,7 +79,7 @@ install( VisualModel.hpp VisualOwnable.hpp VisualResources.hpp - VisualTextModel.cppm + VisualTextModel.hpp VoronoiVisual.cppm win_t.cppm diff --git a/mplot/CoordArrows.cppm b/mplot/CoordArrows.cppm deleted file mode 100644 index 839273ec..00000000 --- a/mplot/CoordArrows.cppm +++ /dev/null @@ -1,181 +0,0 @@ -/*! - * \file - * - * Defines a coordinate arrow class based on VisualModel - * - * \author Seb James - * \date 2019 - */ -module; - -#include -#include -#include - -export module mplot.coordarrows; - -import sm.vec; -import mplot.gl.version; -import mplot.visualcore; -import mplot.textfeatures; -import mplot.visualfont; -import mplot.colour; - -export namespace mplot -{ - //! This class creates the vertices for a set of coordinate arrows to be rendered - //! in a 3-D scene. - template - class CoordArrows : public VisualModel - { - public: - CoordArrows() : mplot::VisualModel() {} - CoordArrows (const sm::vec& offset) : mplot::VisualModel(offset) {} - - //! Must make the boilerplate bindmodel call before calling init() (for text handling) - void init (const sm::vec _lengths, const float _thickness, const float _em) - { - this->compute_bb (false); - this->lengths = _lengths; - this->thickness = _thickness; - this->em = _em; - } - - //! You can call this AS well as the first init overload to set the axis vectors - void init (const sm::vec _x, const sm::vec _y, const sm::vec _z) - { - this->compute_bb (false); - this->x_axis = _x; - this->y_axis = _y; - this->z_axis = _z; - } - - //! Make sure coord arrow colours are ok on the given background colour. Call this *after* finalize. - void setColourForBackground (const std::array& bgcolour) - { - // For now, only worry about the centresphere: - std::array cscol = { 1.0f - bgcolour[0], 1.0f - bgcolour[1], 1.0f - bgcolour[2] }; - if (cscol != this->centresphere_col) { - this->centresphere_col = cscol; - this->reinit(); // sets context, does not release it - - // Give the text labels a suitable, visible colour - mplot::VisualResources::i().setContext (this->parentVis); - auto ti = this->texts.begin(); - while (ti != this->texts.end()) { - (*ti)->setVisibleOn (bgcolour); - ti++; - } - mplot::VisualResources::i().releaseContext(); - } - } - - void initAxisLabels() - { - if (this->em > 0.0f) { - - mplot::VisualResources::i().setContext (this->parentVis); - mplot::TextFeatures tfca(this->em, 48, false, mplot::colour::black, mplot::VisualFont::DVSansItalic); - - // These texts are black by default - sm::vec _offset = this->viewmatrix.translation(); - sm::vec toffset = {}; - toffset = _offset + this->x_axis * this->lengths[0]; - toffset[0] += this->em; - auto vtm1 = this->makeVisualTextModel (tfca); - vtm1->setupText (this->x_label, toffset); - this->texts.push_back (std::move(vtm1)); - toffset = _offset + this->y_axis * this->lengths[1]; - toffset[0] += this->em; - auto vtm2 = this->makeVisualTextModel (tfca); - vtm2->setupText (this->y_label, toffset); - this->texts.push_back (std::move(vtm2)); - toffset = _offset + this->z_axis * this->lengths[2]; - toffset[0] += this->em; - auto vtm3 = this->makeVisualTextModel (tfca); - vtm3->setupText (this->z_label, toffset); - this->texts.push_back (std::move(vtm3)); - - mplot::VisualResources::i().releaseContext(); - } - } - - //! Initialize vertex buffer objects and vertex array object. - void initializeVertices() - { - this->vertexPositions.clear(); - this->vertexNormals.clear(); - this->vertexColors.clear(); - this->indices.clear(); - this->idx = 0; - - // Draw four spheres to make up the coord frame, with centre at 0,0,0 - sm::vec reloffset = {}; - static constexpr sm::vec zerocoord = { 0.0f, 0.0f, 0.0f }; - this->computeSphere (zerocoord, centresphere_col, this->thickness * this->lengths[0] * this->centre_sphere_size); - - // x - reloffset = this->x_axis * this->lengths[0]; - this->computeSphere (reloffset, x_axis_col, this->thickness * this->lengths[0] * this->endsphere_size); - this->computeTube (zerocoord, reloffset, x_axis_col, x_axis_col, this->thickness * this->lengths[0] * this->tube_size); - if (showneg) { - this->computeTube (zerocoord, -reloffset, x_axis_neg, x_axis_neg, this->thickness * this->lengths[0] * this->tube_size); - } - - // y - reloffset = this->y_axis * this->lengths[1]; - this->computeSphere (reloffset, y_axis_col, this->thickness * this->lengths[0] * this->endsphere_size); - this->computeTube (zerocoord, reloffset, y_axis_col, y_axis_col, this->thickness * this->lengths[0] * this->tube_size); - if (showneg) { - this->computeTube (zerocoord, -reloffset, y_axis_neg, y_axis_neg, this->thickness * this->lengths[0] * this->tube_size); - } - - // z - reloffset = this->z_axis * this->lengths[2]; - this->computeSphere (reloffset, z_axis_col, this->thickness * this->lengths[0] * this->endsphere_size); - this->computeTube (zerocoord, reloffset, z_axis_col, z_axis_col, this->thickness * this->lengths[0] * this->tube_size); - if (showneg) { - this->computeTube (zerocoord, -reloffset, z_axis_neg, z_axis_neg, this->thickness * this->lengths[0] * this->tube_size); - } - - this->initAxisLabels(); - } - - //! The lengths of the coordinate arrows - sm::vec lengths = { 1.0f, 1.0f, 1.0f }; - - //! The axes for the coordinate arrows. A simple right handed coordinate system aligned with - //! the 'real' world coordinate system by default. - sm::vec x_axis = sm::vec::ux(); - sm::vec y_axis = sm::vec::uy(); - sm::vec z_axis = sm::vec::uz(); - - //! A thickness scaling factor, to scale all thicknesses at once - float thickness = 1.0f; - //! The radius of the end spheres as a proportion of the length - float endsphere_size = 1.0f / 40.0f; - //! The radius of the centre sphere as a proportion of the length - float centre_sphere_size = 1.0f / 20.0f; - //! The radius of the arrows, as a proportion of the length - float tube_size = 1.0f / 80.0f; - //! m size for text labels - float em = 0.0f; - - //! The colours of the arrows, and of the centre sphere (where default of black is suitable - //! for a white background) - std::array centresphere_col = mplot::colour::black; - std::array x_axis_col = mplot::colour::crimson; - std::array y_axis_col = mplot::colour::springgreen2; - std::array z_axis_col = mplot::colour::blue2; - - bool showneg = false; - std::array x_axis_neg = mplot::colour::raspberry; - std::array y_axis_neg = mplot::colour::darkseagreen3; - std::array z_axis_neg = mplot::colour::steelblue3; - - std::string x_label = "X"; - std::string y_label = "Y"; - std::string z_label = "Z"; - }; - -} // namespace mplot diff --git a/mplot/HexGridVisual.cppm b/mplot/HexGridVisual.cppm index c2b58efc..f6844630 100644 --- a/mplot/HexGridVisual.cppm +++ b/mplot/HexGridVisual.cppm @@ -17,7 +17,7 @@ import sm.scale; export import mplot.gl.version; export import mplot.colourmap; import mplot.tools; -export import mplot.visualcore; +export import mplot.visualcore; // Brings VisualDataModel export namespace mplot { diff --git a/mplot/Visual.cppm b/mplot/Visual.cppm deleted file mode 100644 index a04cf7d8..00000000 --- a/mplot/Visual.cppm +++ /dev/null @@ -1,309 +0,0 @@ -/*! - * \file - * - * Awesome graphics code for high performance graphing and visualisation. - * - * This is the main visual scene class in mathplot and derives from mplot::VisualOwnable, adding - * window handling with GLFW3. - * - * This is the multiple context-safe version of VisualNoMX. - * - * It is further aliased to mplot::Visual in mplot/Visual.h. - * - * Created by Seb James on 2025/03/03 - * - * \author Seb James - * \date May 2025 - */ -module; - -#ifndef _glfw3_h_ // glfw3 has not yet been externally included -# define GLFW_INCLUDE_NONE // Here, we tell GLFW that we will explicitly include GL3/gl3.h and GL/glext.h -# include -#endif // _glfw3_h_ - -#include -#include -#include -#include - -export module mplot.visual; - -export import mplot.gl.version; -export import mplot.win_t; - -import mplot.visualresources; -export import mplot.visualglfw; -export import mplot.visualownable; - -export namespace mplot -{ - /*! - * Visual 'scene' class - * - * A class for visualising computational models on an OpenGL screen. - * - * Each Visual will have its own GLFW window and is essentially a "scene" containing a number - * of objects. One object might be the visualisation of some data expressed over a - * HexGrid. Another could be a GraphVisual object. The class handles mouse events to allow the - * user to rotate and translate the scene, as well as use keys to generate particular - * effects/views. - * - * It's possible to set the background colour of the scene (Visual::bgcolour), the location of - * the objects in the scene (Visual::setSceneTransZ and friends) and the position and field of - * view of the 'camera' (Visual::zNear, Visual::zFar and Visual::fov). - * - * \tparam glver The OpenGL version, encoded as a single int (see mplot::gl::version) - */ - template - class Visual : public mplot::VisualOwnable - { - public: - /*! - * Construct a new visualiser. The rule is 1 window to one Visual object. So, this creates a - * new window and a new OpenGL context. - */ - Visual (const std::int32_t _width, const std::int32_t _height, const std::string& _title, const bool _version_stdout = true) - { - this->window_w = _width; - this->window_h = _height; - this->title = _title; - this->options.set (visual_options::versionStdout, _version_stdout); - - this->init_resources(); - this->init_gl(); // could this come before init_resources? NO, because init_gl has - // VisualTextModel stuff that requires init_resources. Could maybe split init_gl - } - - //! Deconstructor destroys GLFW/Qt window and deregisters access to VisualResources - ~Visual() - { - this->setContext(); - glfwDestroyWindow (this->window); - this->deconstructCommon(); - } - - // Do one-time init of the Visual's resources. This gets/creates the VisualResources, - // registers this visual with resources, calls init_window for any glfw stuff that needs to - // happen, and lastly initializes the freetype code. - void init_resources() - { - mplot::VisualGlfw::i().init(); // Init GLFW windows system - // VisualResources provides font management. Ensure it exists in memory. - mplot::VisualResources::i().create(); - // Connect the static set/releaseContext calls from VisualGlfw to the VisualResources calls - mplot::VisualResources::i().setContext_implementation = mplot::VisualGlfw::setContext; - mplot::VisualResources::i().releaseContext_implementation = mplot::VisualGlfw::releaseContext; - // Set up the window that will present the OpenGL graphics. This has to - // happen BEFORE the call to VisualResources::freetype_init() - this->init_window(); - // Check: when is this->shaders set up? in *init_gl*! So need a set_shaders method in VisualResouces - this->visual_id = mplot::VisualResources::i().register_visual (this->glfn, this->window); - this->setContext(); // For freetype_init - mplot::VisualResources::i().freetype_init (this->visual_id, this->glfn); - this->releaseContext(); - } - - void setSwapInterval() final - { - // Swap as fast as possible (fixes lag of scene with mouse movements) - glfwSwapInterval (0); - } - - //! Make this Visual the current one, so that when creating/adding a visual model, the vao - //! ids relate to the correct OpenGL context. - void setContext() final { glfwMakeContextCurrent (this->window); } - - //! swapBuffers implementation for glfw - void swapBuffers() final { glfwSwapBuffers (this->window); } - - //! Lock the context to prevent accessing the OpenGL context from multiple threads - //! then obtain the context. - void lockContext() - { - this->context_mutex.lock(); - this->setContext(); - } - - //! Attempt to lock the context. If the mutex lock is obtained, set the OpenGL - //! context and return true. If the mutex lock is not obtained, return false. - bool tryLockContext() - { - if (this->context_mutex.try_lock()) { - this->setContext(); - return true; - } - return false; - } - - //! Release the OpenGL context and unlock the context mutex. - void unlockContext() - { - this->releaseContext(); - this->context_mutex.unlock(); - } - - //! Release the OpenGL context - void releaseContext() final { glfwMakeContextCurrent (nullptr); } - - /*! - * \brief OpenGL context check - * - * You can see if the OpenGL context is held at any time in your program. This function - * returns true if there is a non-null window and we currently 'have that context'. This - * should return true after a call to Visual::setContext and false after a call to - * Visual::releaseContext. - */ - bool checkContext() - { - return this->window == nullptr ? false : (glfwGetCurrentContext() == this->window); - } - - //! Obtain the window pointer - win_t* getWindow() { return this->window; } - - /* - * A note on setContext() in keepOpen/poll/waitevents/wait: - * - * I considered automatically calling setContext in these functions. However, the event - * queue is not necessarily bound to the context (it depends on the platform), so I will - * leave these as they are. The call to render() inside keepOpen() WILL correctly induce a - * setContext() call. - */ - - /*! - * Keep on rendering until readToFinish is set true. Used to keep a window open, and - * responsive, while displaying the result of a simulation. FIXME: This won't work for two - * or more windows because it will block. - */ - void keepOpen() - { - while (this->state.test (visual_state::readyToFinish) == false) { - glfwWaitEventsTimeout (0.01667); // 16.67 ms ~ 60 Hz - this->render(); - } - } - - /*! - * Like keepOpen, but renders until paused is set false (or user signals they're ready to - * finish), then returns. - */ - void pauseOpen() - { - this->state.set (visual_state::paused); - while (this->state.test (visual_state::paused) == true && this->state.test (visual_state::readyToFinish) == false) { - glfwWaitEventsTimeout (0.01667); // 16.67 ms ~ 60 Hz - this->render(); - } - } - - //! Wrapper around the glfw polling function - void poll() { glfwPollEvents(); } - //! A wait-for-events with a timeout wrapper - void waitevents (const double& timeout) { glfwWaitEventsTimeout (timeout); } - //! Collect events for timeout, returning after *all* the time elapsed - void wait (const double& timeout) - { - using sc = std::chrono::steady_clock; - sc::time_point t0 = sc::now(); - sc::time_point t1 = sc::now(); - std::int32_t timeout_us = timeout * 1000000; - while (std::chrono::duration_cast(t1 - t0).count() < timeout_us) { - glfwWaitEventsTimeout (timeout/10.0); - t1 = sc::now(); - } - } - - private: - - void init_window() - { - this->window = glfwCreateWindow (this->window_w, this->window_h, this->title.c_str(), NULL, NULL); - if (!this->window) { - // Window or OpenGL context creation failed - throw std::runtime_error("GLFW window creation failed!"); - } - // now associate "this" object with mWindow object - glfwSetWindowUserPointer (this->window, this); - - // Set up callbacks - glfwSetKeyCallback (this->window, key_callback_dispatch); - glfwSetMouseButtonCallback (this->window, mouse_button_callback_dispatch); - glfwSetCursorPosCallback (this->window, cursor_position_callback_dispatch); - glfwSetWindowSizeCallback (this->window, window_size_callback_dispatch); - glfwSetWindowContentScaleCallback (this->window, window_content_scale_callback_dispatch); - glfwSetWindowCloseCallback (this->window, window_close_callback_dispatch); - glfwSetScrollCallback (this->window, scroll_callback_dispatch); - - glfwMakeContextCurrent (this->window); - glfwGetWindowContentScale (this->window, &this->window_scale_w, &this->window_scale_h); - - this->init_glad (glfwGetProcAddress); - } - - private: - //! Context mutex to prevent contexts being acquired in a non-threadsafe manner. - std::mutex context_mutex; - - /* - * GLFW callback dispatch functions - */ - static void key_callback_dispatch (GLFWwindow* _window, std::int32_t key, std::int32_t scancode, std::int32_t action, std::int32_t mods) - { - Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); - if (self->key_callback (key, scancode, action, mods)) { - self->render(); - } - } - static void mouse_button_callback_dispatch (GLFWwindow* _window, std::int32_t button, std::int32_t action, std::int32_t mods) - { - Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); - self->mouse_button_callback (button, action, mods); - } - static void cursor_position_callback_dispatch (GLFWwindow* _window, double x, double y) - { - Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); - if (self->cursor_position_callback (x, y)) { - self->render(); - } - } - static void window_size_callback_dispatch (GLFWwindow* _window, std::int32_t width, std::int32_t height) - { - Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); - if (self->window_size_callback (width, height)) { - self->render(); - } - } - static void window_content_scale_callback_dispatch (GLFWwindow* _window, float xscl, float yscl) - { - Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); - if (self->window_content_scale_callback (xscl, yscl)) { - self->render(); - } - } - static void window_close_callback_dispatch (GLFWwindow* _window) - { - Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); - self->window_close_callback(); - } - static void scroll_callback_dispatch (GLFWwindow* _window, double xoffset, double yoffset) - { - Visual* self = static_cast*>(glfwGetWindowUserPointer (_window)); - if (self->scroll_callback (xoffset, yoffset)) { - self->render(); - } - } - - - public: - - /* - * Generic callback handlers - */ - virtual bool key_callback (std::int32_t _key, std::int32_t scancode, std::int32_t action, std::int32_t mods) - { - return mplot::VisualOwnable::template key_callback (_key, scancode, action, mods); - } - }; - -} // namespace mplot diff --git a/mplot/Visual.hpp b/mplot/Visual.hpp index c2787216..b9a9b559 100644 --- a/mplot/Visual.hpp +++ b/mplot/Visual.hpp @@ -27,12 +27,13 @@ #include #include -#include -#include +// Or better import mplot.visualcore; +//#include +//#include +import mplot.visualcore; import mplot.gl.version; import mplot.win_t; - import mplot.visualglfw; namespace mplot diff --git a/mplot/VisualDataModel.cppm b/mplot/VisualDataModel.cppm deleted file mode 100644 index 49246ec9..00000000 --- a/mplot/VisualDataModel.cppm +++ /dev/null @@ -1,454 +0,0 @@ -/*! - * VisualModels which have data. - */ -module; - -#include -#include -#include - -export module mplot.visualdatamodel; - -export import sm.vec; -export import sm.vvec; -export import sm.scale; -import sm.centroid; - -export import mplot.visualcore; -export import mplot.colourmap; -export import mplot.gl.version; - -export namespace mplot -{ - // How should a VisualDataModel visualize complex data? - enum class complex_number_handling : std::uint32_t - { - as_real_scalar, - as_imaginary_scalar, - as_magnitude_scalar, - as_phase_scalar, - // many ways to do this. magnitude = z, phase = colour; colour from real/imag colour from mag/phase - as_colour_phase_magnitude_z, // two scalars - as_colour_vector_real_imaginary, - as_colour_vector_magnitude_phase - }; - - //! VisualDataModel implementation base class containing common functionality - all the - //! sm::scale objects and methods. - template - struct VisualDataModel_impl_base : public VisualModel - { - VisualDataModel_impl_base() : mplot::VisualModel::VisualModel() {} - VisualDataModel_impl_base (const sm::vec _offset) : mplot::VisualModel::VisualModel (_offset) {} - //! Deconstructor should *not* deallocate data - client code should do that - ~VisualDataModel_impl_base() {} - - //! Reset the autoscaled flags so that the next time data is transformed by - //! the Scale objects they will autoscale again (assuming they have - //! do_autoscale set true). - void clearAutoscale() - { - if (this->zScale.do_autoscale == true) { this->zScale.reset(); } - if (this->colourScale.do_autoscale == true) { this->colourScale.reset(); } - if (this->colourScale2.do_autoscale == true) { this->colourScale2.reset(); } - if (this->colourScale3.do_autoscale == true) { this->colourScale3.reset(); } - if (this->vectorScale.do_autoscale == true) { this->vectorScale.reset(); } - } - - void clearAutoscaleZ() { if (this->zScale.do_autoscale == true) { this->zScale.reset(); } } - void clearAutoscaleColour() - { - if (this->colourScale.do_autoscale == true) { this->colourScale.reset(); } - if (this->colourScale2.do_autoscale == true) { this->colourScale2.reset(); } - if (this->colourScale3.do_autoscale == true) { this->colourScale3.reset(); } - } - void clearAutoscaleVector() { if (this->vectorScale.do_autoscale == true) { this->vectorScale.reset(); } } - - void setZScale (const sm::scale& zscale) { this->zScale = zscale; } - void setCScale (const sm::scale& cscale) { this->colourScale = cscale; } - - void updateZScale (const sm::scale& zscale) - { - this->zScale = zscale; - this->reinit(); - } - - void updateCScale (const sm::scale& cscale) - { - this->colourScale = cscale; - this->reinit(); - } - - void setVectorScale (const sm::scale>& vscale) - { - this->vectorScale = vscale; - this->reinit(); - } - - void setColourMap (ColourMapType _cmt, const float _hue = 0.0f) - { - this->cm.setHue (_hue); - this->cm.setType (_cmt); - } - - //! An overridable function to set the colour of rect ri - std::array setColour (std::uint64_t ri) - { - std::array clr = { 0.0f, 0.0f, 0.0f }; - if (this->cm.numDatums() == 3) { - if constexpr (std::is_integral>::value) { - // Differs from above as we divide by 255 to get value in range 0-1 - clr = this->cm.convert (this->dcolour[ri]/255.0f, this->dcolour2[ri]/255.0f, this->dcolour3[ri]/255.0f); - } else { - clr = this->cm.convert (this->dcolour[ri], this->dcolour2[ri], this->dcolour3[ri]); - } - } else if (this->cm.numDatums() == 2) { - // Use vectorData - clr = this->cm.convert (this->dcolour[ri], this->dcolour2[ri]); - } else { - clr = this->cm.convert (this->dcolour[ri]); - } - return clr; - } - - //! All data models use a a colour map. Change the type/hue of this colour map - //! object to generate different types of map. - ColourMap cm; - - //! A Scaling function for the colour map. Perhaps a scale class contains a - //! colour map? If not, then this scale might well be autoscaled. Applied to scalarData. - sm::scale colourScale; - //! Scale for second colour (when used with vectorData). This is used if the ColourMap cm is - //! ColourMapType::DuoChrome of ColourMapType::HSV. - sm::scale colourScale2; - //! scale for third colour (when used with vectorData). Use if ColourMap cm is - //! ColourMapType::TriChrome. - sm::scale colourScale3; - - //! A scale to scale (or autoscale) scalarData. This might be used to set z - //! locations of data coordinates based on scalarData. The scaling may - sm::scale zScale; - - //! A scaling function for the vectorData. This will scale the lengths of the - //! vectorData. - sm::scale> vectorScale; - - //! If visualizing vector of complex, how to treat/visualize the data? - mplot::complex_number_handling complexHandling = mplot::complex_number_handling::as_real_scalar; - - /* - * Scaled data. Used in GridVisual classes and PolarVisual or anywhere else where scalarData - * or vectorData are scaled to be z values or colours. - */ - - //! A copy of the scalarData which can be transformed suitably to be the z value of the surface - sm::vvec dcopy; - //! A copy of the scalarData (or first field of vectorData), scaled to be a colour value - sm::vvec dcolour; - //! For the second field of vectorData - sm::vvec dcolour2; - //! For the third field of vectorData - sm::vvec dcolour3; - - //! The length of the data structure that will be visualized. May be length of - //! this->scalarData or of this->vectorData. - std::uint32_t datasize = 0; - }; - - //! VisualDataModel implementation that deals with std::vector pointers to scalar/vector data - template - struct VisualDataModel_impl : public VisualDataModel_impl_base - { - void setScalarData (const std::vector* _data) { this->scalarData = _data; } - void setVectorData (const std::vector>* _vectors) { this->vectorData = _vectors; } - void setDataCoords (std::vector>* _coords) { this->dataCoords = _coords; } - void setComplexData (const std::vector>* _data) { this->complexData = _data; } - - //! Update the scalar data - virtual void updateData (const std::vector* _data) - { - this->scalarData = _data; - this->reinit(); - } - - //! Update the scalar data with an associated z-scaling - void updateData (const std::vector* _data, const sm::scale& zscale) - { - this->scalarData = _data; - this->zScale = zscale; - this->reinit(); - } - - //! Update the scalar data, along with both the z-scaling and the colour-scaling - void updateData (const std::vector* _data, const sm::scale& zscale, const sm::scale& cscale) - { - this->scalarData = _data; - this->zScale = zscale; - this->colourScale = cscale; - this->reinit(); - } - - virtual void updateData (const std::vector>* _data) - { - this->complexData = _data; - this->reinit(); - } - - - //! Update coordinate data and scalar data along with z-scaling for scalar data - virtual void updateData (std::vector>* _coords, const std::vector* _data, - const sm::scale& zscale) - { - this->dataCoords = _coords; - this->scalarData = _data; - this->zScale = zscale; - this->reinit(); - } - - //! Update coordinate data and scalar data along with z- and colour-scaling for scalar data - virtual void updateData (std::vector>* _coords, const std::vector* _data, - const sm::scale& zscale, const sm::scale& cscale) - { - this->dataCoords = _coords; - this->scalarData = _data; - this->zScale = zscale; - this->colourScale = cscale; - this->reinit(); - } - - //! Update just the coordinate data - virtual void updateCoords (std::vector>* _coords) - { - this->dataCoords = _coords; - this->reinit(); - } - - //! Update the vector data (for plotting quiver plots) - void updateData (const std::vector>* _vectors) - { - this->vectorData = _vectors; - this->reinit(); - } - - //! Update both coordinate and vector data - void updateData (std::vector>* _coords, const std::vector>* _vectors) - { - this->dataCoords = _coords; - this->vectorData = _vectors; - this->reinit(); - } - - //! Find datasize - void determine_datasize() - { - this->datasize = 0; - if (this->vectorData != nullptr && !this->vectorData->empty()) { - this->datasize = this->vectorData->size(); - } else if (this->scalarData != nullptr && !this->scalarData->empty()) { - this->datasize = this->scalarData->size(); - } else if (this->complexData != nullptr && !this->complexData->empty()) { - this->datasize = this->complexData->size(); - } // else datasize remains 0 - } - - // Common function for setting up the z and colour scaling - void setupScaling() - { - this->dcopy.resize (this->datasize, 0.0f); - this->dcolour.resize (this->datasize); - - if (this->scalarData != nullptr) { - // What do these scaling operations do to any NaNs in scalarData? They should remain - // NaN. Then in dcopy, might want to make them 0. - this->zScale.transform (*(this->scalarData), this->dcopy); - this->dcopy.replace_nan_with (this->zScale.transform_one(0.0f)); - this->colourScale.transform (*(this->scalarData), this->dcolour); - - } else if (this->complexData != nullptr) { - if (this->complexHandling == mplot::complex_number_handling::as_colour_vector_real_imaginary - || this->complexHandling == mplot::complex_number_handling::as_colour_vector_magnitude_phase) { - - // No need to worry about scaling colourScale here, as dcolour/dcolour2 are autoscaled later. - - this->dcolour2.resize (this->datasize); - this->dcolour3.resize (this->datasize); // though we won't use this - sm::vvec veclens(this->dcopy); - if (this->complexHandling == mplot::complex_number_handling::as_colour_vector_real_imaginary) { - for (std::uint32_t i = 0; i < this->datasize; ++i) { - veclens[i] = std::abs((*this->complexData)[i]); - this->dcolour[i] = std::real ((*this->complexData)[i]); - this->dcolour2[i] = std::imag ((*this->complexData)[i]); - } - } else { - for (std::uint32_t i = 0; i < this->datasize; ++i) { - veclens[i] = std::abs((*this->complexData)[i]); - this->dcolour[i] = std::abs ((*this->complexData)[i]); - this->dcolour2[i] = std::arg ((*this->complexData)[i]); - } - } - this->zScale.transform (veclens, this->dcopy); - - } else if (this->complexHandling == mplot::complex_number_handling::as_colour_phase_magnitude_z) { - - // As we call transform_one, we have to first loop through and 'manually - // autoscale' if scaling was not already set by the client code. - if (this->zScale.ready() == false || this->colourScale.ready() == false) { - auto inrange = sm::interval::search_initialized(); - auto col_inrange = sm::interval::search_initialized(); - for (std::uint32_t i = 0; i < this->datasize; ++i) { - inrange.update (std::abs ((*this->complexData)[i])); - col_inrange.update (std::arg ((*this->complexData)[i])); - } - if (this->zScale.ready() == false) { - this->zScale.compute_scaling (inrange); - } - if (this->colourScale.ready() == false) { - this->colourScale.compute_scaling (col_inrange); - } - } - - for (std::uint32_t i = 0; i < this->datasize; ++i) { - this->dcopy[i] = this->zScale.transform_one (std::abs ((*this->complexData)[i])); - if (std::isnan(this->dcopy[i])) { this->dcopy[i] = this->zScale.transform_one(0.0f); } - this->dcolour[i] = this->colourScale.transform_one (std::arg ((*this->complexData)[i])); - } - } else { - - // As we call transform_one, we have to first loop through and 'manually - // autoscale' if scaling was not already set by the client code. - if (this->zScale.ready() == false || this->colourScale.ready() == false) { - auto inrange = sm::interval::search_initialized(); - for (std::uint32_t i = 0; i < this->datasize; ++i) { - if (this->complexHandling == mplot::complex_number_handling::as_real_scalar) { - inrange.update (std::real ((*this->complexData)[i])); - } else if (this->complexHandling == mplot::complex_number_handling::as_imaginary_scalar) { - inrange.update (std::imag ((*this->complexData)[i])); - } else if (this->complexHandling == mplot::complex_number_handling::as_magnitude_scalar) { - inrange.update (std::abs ((*this->complexData)[i])); - } else if (this->complexHandling == mplot::complex_number_handling::as_phase_scalar) { - inrange.update (std::arg ((*this->complexData)[i])); - } // do nothing - } - if (this->colourScale.ready() == false) { - this->colourScale.compute_scaling (inrange); - } - if (this->zScale.ready() == false) { - this->zScale.compute_scaling (inrange); - } - } - - for (std::uint32_t i = 0; i < this->datasize; ++i) { - T _in = T{0}; - if (this->complexHandling == mplot::complex_number_handling::as_real_scalar) { - _in = std::real ((*this->complexData)[i]); - } else if (this->complexHandling == mplot::complex_number_handling::as_imaginary_scalar) { - _in = std::imag ((*this->complexData)[i]); - } else if (this->complexHandling == mplot::complex_number_handling::as_magnitude_scalar) { - _in = std::abs ((*this->complexData)[i]); - } else if (this->complexHandling == mplot::complex_number_handling::as_phase_scalar) { - _in = std::arg ((*this->complexData)[i]); - } else { - throw std::runtime_error ("VisualDataModel: Unhandled complex_number_handling type"); - } - this->dcopy[i] = this->zScale.transform_one (_in); - if (std::isnan(this->dcopy[i])) { this->dcopy[i] = this->zScale.transform_one(0.0f); } - this->dcolour[i] = this->colourScale.transform_one (_in); - } - } - - } else if (this->vectorData != nullptr) { - - this->dcolour2.resize (this->datasize); - this->dcolour3.resize (this->datasize); - sm::vvec veclens(this->dcopy); - for (std::uint32_t i = 0; i < this->datasize; ++i) { - veclens[i] = (*this->vectorData)[i].length(); - this->dcolour[i] = (*this->vectorData)[i][0]; - this->dcolour2[i] = (*this->vectorData)[i][1]; - // Could also extract a third colour for Trichrome vs Duochrome (or for raw RGB signal) - this->dcolour3[i] = (*this->vectorData)[i][2]; - } - this->zScale.transform (veclens, this->dcopy); - } - - if (this->vectorData != nullptr - || (this->complexData != nullptr - && (this->complexHandling == mplot::complex_number_handling::as_colour_vector_real_imaginary - || this->complexHandling == mplot::complex_number_handling::as_colour_vector_magnitude_phase))) { - // Handle case where this->cm.getType() == mplot::ColourMapType::RGB and there is - // exactly one colour. ColourMapType::RGB (and RGBMono/Grey) assumes R/G/B data all - // in range 0->1 ALREADY and therefore they don't need to be re-scaled with - // this->colourScale. - if (this->cm.getType() != mplot::ColourMapType::RGB - && this->cm.getType() != mplot::ColourMapType::RGBMono - && this->cm.getType() != mplot::ColourMapType::RGBGrey) { - this->colourScale.transform (this->dcolour, this->dcolour); - // Dual axis colour maps like Duochrome and HSV will need to use colourScale2 to - // transform their second colour/axis, - this->colourScale2.transform (this->dcolour2, this->dcolour2); - // Similarly for Triple axis maps - this->colourScale3.transform (this->dcolour3, this->dcolour3); - } // else assume dcolour/dcolour2/dcolour3 are all in range 0->1 (or 0-255) already - } - } - - sm::vec coordsCentroid() const { return sm::algo::centroid (*this->dataCoords); } - - /*! - * Scalar data to visualize. T may simply be float or double. - */ - const std::vector* scalarData = nullptr; - - /*! - * Complex valued data to visualize. One may wish to: - * - * * treat complex as if it were scalar, and use just the real component - * * treat complex as if it were scalar and use just the imaginary component - * * treat complex as if it were scalar and use the magnitude - * * treat complex as if it were scalar and use the phase - * * treat complex as a 2D vector and visulize in several possible ways - */ - const std::vector>* complexData = nullptr; - - /*! - * Vector data to visualize (possibly as colour info, possibly as quiver direction) - */ - const std::vector>* vectorData = nullptr; - - /*! - * The coordinates at which to visualize data, if appropriate (e.g. scatter graph, quiver - * plot). Note fixed type of float, which is suitable for OpenGL coordinates. Not const as - * child code may resize or update content. - */ - std::vector>* dataCoords = nullptr; - }; - -#if 0 // We could add another implementation here, in which the data are provided as std::span - - //! VisualDataModel implementation that deals with std::spans to scalar/vector data - template - struct VisualDataModel_impl<1, T, glver> : public VisualDataModel_impl_base - { - // span functions - void setScalarData (std::span _data) { this->scalarData = _data; } - // ...etc - - // span attributes instead of the std::vector<>* - std::span scalarData; - std::span> vectorData; - std::span> dataCoords; - }; -#endif - - /*! - * VisualDataModel is an optional 'data layer' for VisualModels. It is used in several of the - * built-in VisualModels such as HexGridVisual, GridVisual and ScatterVisual. It provides a way - * to refer to the data (such as using std::vector<> pointers) and all the scaling functions - * that are useful for turning the data into colours and positions in the scene. It is not - * necessary to use VisualDataModel as your base class; you can derive directly from VisualModel - * (for an example see InstancedScatterVisual) - */ - template - struct VisualDataModel : public VisualDataModel_impl<0, T, glver> {}; - -} // namespace mplot diff --git a/mplot/VisualModel.cppm b/mplot/VisualModel.cppm deleted file mode 100644 index 4c524a30..00000000 --- a/mplot/VisualModel.cppm +++ /dev/null @@ -1,3949 +0,0 @@ -/*! - * \file - * - * Declares a VisualModel base class to hold the vertices that make up some individual model object - * that can be part of an OpenGL scene. - * - * GL function calls are added in VisualModel.h - * - * \author Seb James - * \date March 2025 - */ -module; - -#if defined __gl3_h_ || defined __gl_h_ -// GL headers have been externally included -#else -# include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -export module mplot.visualmodel; - -export import sm.mathconst; -import sm.geometry; -import sm.geometry_polyhedra; -export import sm.quaternion; -export import sm.mat; -export import sm.vec; -export import sm.vvec; -export import sm.interval; -import sm.algo; -import sm.flags; -import sm.base64; - -// Need to import common here -export import mplot.gl.version; -export import mplot.visualcommon; -export import mplot.visualresources; -export import mplot.visualtextmodel; -export import mplot.colour; -import mplot.gl.util; -import mplot.tools; - -export import mplot.navmesh; - -export namespace mplot -{ - union float_bytes // for gltf output - { - float f; - std::uint8_t bytes[sizeof(float)]; - }; - - /*! - * An OpenGL model class - * - * This class is the 'OpenGL model' class. It has the common code to create the vertices for - * some individual OpenGL model which is to be rendered in a 3-D scene. - * - * Some OpenGL models are derived directly from VisualModel; see for example mplot::CoordArrows. - * - * Other models in mathplot are derived via mplot::VisualDataModel, which adds a common - * mechanism for managing the data which is to be visualised by the final 'Visual' object (such - * as mplot::HexGridVisual or mplot::ScatterVisual) - * - * This class contains some common 'object primitives' code, such as computeSphere and - * computeCone, which compute the vertices that will make up sphere and cone, respectively. - */ - template - struct VisualModel - { - VisualModel() {} - VisualModel (const sm::vec _offset) { this->viewmatrix.translate (_offset); } - - //! destroy gl buffers in the deconstructor - virtual ~VisualModel() // clang gives -Wdelete-non-abstract-non-virtual-dtor without virtual - { - // Explicitly clear owned VisualTextModels - this->texts.clear(); - if (this->vbos != nullptr) { - GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - if (glfn) { - glfn->DeleteBuffers (this->numVBO, this->vbos.get()); - glfn->DeleteVertexArrays (1, &this->vao); - } - } - } - - //! Common code to call after the vertices have been set up. GL has to have been initialised. - void postVertexInit() - { - if (this->parentVis == std::numeric_limits::max()) { - throw std::runtime_error ("parentVis is unset"); - } - GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - - // Do gl memory allocation of vertex array once only - if (this->vbos == nullptr) { - // Create vertex array object - glfn->GenVertexArrays (1, &this->vao); // Safe for OpenGL 4.4- - } - glfn->BindVertexArray (this->vao); - - // Create the vertex buffer objects (once only) - if (this->vbos == nullptr) { - this->vbos = std::make_unique(this->numVBO); - glfn->GenBuffers (this->numVBO, this->vbos.get()); // OpenGL 4.4- safe - } - - // Set up the indices buffer - bind and buffer the data in this->indices - glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]); - - std::size_t sz = this->indices.size() * sizeof(std::uint32_t); - glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW); - - // Binds data from the "C++ world" to the OpenGL shader world for - // "position", "normalin" and "color" - // (bind, buffer and set vertex array object attribute) - this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc, 3); - this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc, 3); - this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc, this->ncol); - - // Unbind only the vertex array (not the buffers, that causes GL_INVALID_ENUM errors) - glfn->BindVertexArray(0); // carefully unbind and rebind - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - - if (this->flags.test (vm_bools::instanced)) { - // Here, we cause the SSBOs to be intialized if they haven't already, and we reserve - // some space in the SSBOs for *this model* - this->instance_start = mplot::VisualResources::i().init_instance_ssbo (this->parentVis, this->max_instances); - if (this->instance_start == std::numeric_limits::max()) { - throw std::runtime_error ("Failed to reserve space in SSBO"); - } - } - - /* - * Now do the same for the bounding box - */ - if (this->flags.test (vm_bools::compute_bb)) { - - if (this->vbos_bb == nullptr) { glfn->GenVertexArrays (1, &this->vao_bb); } - glfn->BindVertexArray (this->vao_bb); - - // Create the vertex buffer objects (once only) - if (this->vbos_bb == nullptr) { - this->vbos_bb = std::make_unique(this->numVBO); - glfn->GenBuffers (this->numVBO, this->vbos_bb.get()); - } - - // Set up the indices buffer - bind and buffer the data in this->indices - glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos_bb[this->idxVBO]); - - std::size_t sz = this->indices_bb.size() * sizeof(std::uint32_t); - glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices_bb.data(), GL_STATIC_DRAW); - - // Binds data from the "C++ world" to the OpenGL shader world for - // "position", "normalin" and "color" - // (bind, buffer and set vertex array object attribute) - this->setupVBO (this->vbos_bb[this->posnVBO], this->vpos_bb, visgl::posnLoc, 3); - this->setupVBO (this->vbos_bb[this->normVBO], this->vnorm_bb, visgl::normLoc, 3); - this->setupVBO (this->vbos_bb[this->colVBO], this->vcol_bb, visgl::colLoc, this->ncol); - - // Unbind only the vertex array (not the buffers, that causes GL_INVALID_ENUM errors) - glfn->BindVertexArray(0); // carefully unbind and rebind - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - } - - this->flags.set (vm_bools::postVertexInitRequired, false); - } - - //! Initialize vertex buffer objects and vertex array object. Empty for 'text only' VisualModels. - virtual void initializeVertices() {}; - /*! - * Helper to make a VisualTextModel and set its parent so it is ready for use. - * - * You could write it out explicitly as: - * - * std::unique_ptr> vtm1 = this->makeVisualTextModel (tfca); - * - * Or use auto to help: - * - * auto vtm1 = this->makeVisualTextModel (tfca); - * - * See GraphVisual.h for examples. - */ - std::unique_ptr> makeVisualTextModel(const mplot::TextFeatures& tf) - { - auto tmup = std::make_unique> (tf); - tmup->set_parent (this->parentVis); - return tmup; - } - - /*! - * Add a text label to the model at location (within the model coordinates) - * toffset. Return the text geometry of the added label so caller can place - * associated text correctly. Control font size, resolution, colour and font - * face with TextFeatures tf. - */ - mplot::TextGeometry addLabel (const std::string& _text, - const sm::vec& _toffset, - const mplot::TextFeatures& tf = mplot::TextFeatures()) - { - if (mplot::VisualResources::i().get_tprog (this->parentVis) == 0) { - throw std::runtime_error ("No text shader prog. Did your VisualModel-derived class set it up?"); - } - - mplot::VisualResources::i().setContext (this->parentVis); // For VisualTextModel - - auto tmup = this->makeVisualTextModel (tf); - - if (tf.centre_horz == true) { - mplot::TextGeometry tg = tmup->getTextGeometry(_text); - sm::vec centred_locn = _toffset; - centred_locn[0] -= tg.half_width(); - tmup->setupText (_text, centred_locn + this->viewmatrix.translation(), tf.colour); - } else { - tmup->setupText (_text, _toffset + this->viewmatrix.translation(), tf.colour); - } - - this->texts.push_back (std::move(tmup)); - - // As this is a setup function, release the context - mplot::VisualResources::i().releaseContext(); - - return this->texts.back()->getTextGeometry(); - } - - /*! - * Add a text label, with given offset _toffset and the specified tf. The - * reference to a pointer, tm, allows client code to change the text of the - * VisualTextModel as necessary, after the label has been added. - */ - mplot::TextGeometry addLabel (const std::string& _text, - const sm::vec& _toffset, - mplot::VisualTextModel*& tm, - const mplot::TextFeatures& tf = mplot::TextFeatures()) - { - if (mplot::VisualResources::i().get_tprog (this->parentVis) == 0) { - throw std::runtime_error ("No text shader prog. Did your VisualModel-derived class set it up?"); - } - - mplot::VisualResources::i().setContext (this->parentVis); // For VisualTextModel - - auto tmup = this->makeVisualTextModel (tf); - - if (tf.centre_horz == true) { - mplot::TextGeometry tg = tmup->getTextGeometry(_text); - sm::vec centred_locn = _toffset; - centred_locn[0] -= tg.half_width(); - tmup->setupText (_text, centred_locn + this->viewmatrix.translation(), tf.colour); - } else { - tmup->setupText (_text, _toffset + this->viewmatrix.translation(), tf.colour); - } - - this->texts.push_back (std::move(tmup)); - tm = this->texts.back().get(); - - // As this is a setup function, release the context - mplot::VisualResources::i().releaseContext(); - - return this->texts.back()->getTextGeometry(); - } - - void setSceneMatrixTexts (const sm::mat& sv) - { - auto ti = this->texts.begin(); - while (ti != this->texts.end()) { (*ti)->setSceneMatrix (sv); ti++; } - } - - void setSceneTranslationTexts (const sm::vec& v0) - { - auto ti = this->texts.begin(); - while (ti != this->texts.end()) { (*ti)->setSceneTranslation (v0); ti++; } - } - - void setViewRotationTexts (const sm::quaternion& r) - { - // When rotating a model that contains texts, we need to rotate the scene - // for the texts and also inverse-rotate the view of the texts. - auto ti = this->texts.begin(); - while (ti != this->texts.end()) { - // Rotate the scene. Note this won't work if the VisualModel has a - // translation away from the origin. - (*ti)->setSceneRotation (r); // Need this to rotate about _offset. BUT the - // translation is already there in the text, - // but in the MODEL view. - - // Rotate the view of the text an opposite amount, to keep it facing forwards - (*ti)->setViewRotation (r.invert()); - ti++; - } - } - - void addViewRotationTexts (const sm::quaternion& r) - { - auto ti = this->texts.begin(); - while (ti != this->texts.end()) { (*ti)->addViewRotation (r); ti++; } - } - - //! Process vertices and find the bounding box - void update_bb() - { - if (this->flags.test (vm_bools::compute_bb) == false) { return; } - - if (this->vertexPositions.size() % 3 != 0) { - throw std::runtime_error ("VisualModelBase: vertexPositions size is not divisible by 3"); - } - this->bb.search_init(); - for (std::size_t i = 0; i < this->vertexPositions.size(); i += 3) { - this->bb.update (sm::vec{ vertexPositions[i], vertexPositions[i+1], vertexPositions[i+2] }); - } - // Construct the half-extent axis vectors, too. - const sm::vec bb_ext = this->bb.span() / 2.0f; - this->bb_x = { bb_ext[0], 0, 0 }; // i.e. bb_ext[0] * sm::vec<>::ux(); - this->bb_y = { 0, bb_ext[1], 0 }; - this->bb_z = { 0, 0, bb_ext[2] }; - - // After finding the bounding box, make up the vertices to display it: - this->computeBoundingBox(); - } - - /*! - * Re-initialize the buffers. Client code might have appended to - * vertexPositions/Colors/Normals and indices before calling this method. - */ - void reinit_buffers() - { - GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - - mplot::VisualResources::i().setContext (this->parentVis); - if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); } - - // Now re-set up the VBOs - glfn->BindVertexArray (this->vao); // carefully unbind and rebind - glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]); // carefully unbind and rebind - - std::size_t sz = this->indices.size() * sizeof(std::uint32_t); - glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW); - this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc, 3); - this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc, 3); - this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc, this->ncol); - - glfn->BindVertexArray(0); // carefully unbind and rebind - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); // carefully unbind and rebind - - // Optional bounding box - if (this->flags.test (vm_bools::compute_bb)) { - glfn->BindVertexArray (this->vao_bb); - glfn->BindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->vbos_bb[this->idxVBO]); - - std::size_t sz = this->indices_bb.size() * sizeof(std::uint32_t); - glfn->BufferData (GL_ELEMENT_ARRAY_BUFFER, sz, this->indices_bb.data(), GL_STATIC_DRAW); - this->setupVBO (this->vbos_bb[this->posnVBO], this->vpos_bb, visgl::posnLoc, 3); - this->setupVBO (this->vbos_bb[this->normVBO], this->vnorm_bb, visgl::normLoc, 3); - this->setupVBO (this->vbos_bb[this->colVBO], this->vcol_bb, visgl::colLoc, this->ncol); - - glfn->BindVertexArray(0); - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - } - } - - //! reinit ONLY vertexColors buffer - void reinit_colour_buffer() - { - mplot::VisualResources::i().setContext (this->parentVis); - if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); } - GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - // Now re-set up the VBOs - glfn->BindVertexArray (this->vao); // carefully unbind and rebind - this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc, this->ncol); - glfn->BindVertexArray(0); // carefully unbind and rebind - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - } - - void clearTexts() { this->texts.clear(); } - - //! Clear out the model, *including text models* - void clear() - { - this->vertexPositions.clear(); - this->vertexNormals.clear(); - this->vertexColors.clear(); - this->indices.clear(); - this->clearTexts(); - this->idx = 0u; - // Clear bounding box - this->vpos_bb.clear(); - this->vnorm_bb.clear(); - this->vcol_bb.clear(); - this->indices_bb.clear(); - this->idx_bb = 0u; - - this->reinit_buffers(); - } - - //! Re-create the model - called after updating data - void reinit() - { - mplot::VisualResources::i().setContext (this->parentVis); - // Fixme: Better not to clear, then repeatedly pushback here: - this->vertexPositions.clear(); - this->vertexNormals.clear(); - this->vertexColors.clear(); - this->indices.clear(); - - // Clear any bounding box too - this->vpos_bb.clear(); - this->vnorm_bb.clear(); - this->vcol_bb.clear(); - this->indices_bb.clear(); - this->idx_bb = 0u; - - // NB: Do NOT call clearTexts() here! We're only updating the model itself. - this->idx = 0u; - this->initializeVertices(); - // Add additional meshgroups - for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); } - this->update_bb(); - this->reinit_buffers(); - } - - /*! - * For some models it's important to clear the texts when reinitialising. This is NOT the - * same as VisualModel::clear() followed by initializeVertices(). For the same effect, you - * can call clearTexts() then reinit(). - */ - void reinit_with_clearTexts() - { - mplot::VisualResources::i().setContext (this->parentVis); - this->vertexPositions.clear(); - this->vertexNormals.clear(); - this->vertexColors.clear(); - this->indices.clear(); - - this->clearTexts(); - this->idx = 0u; - - // Clear any bounding box too - this->vpos_bb.clear(); - this->vnorm_bb.clear(); - this->vcol_bb.clear(); - this->indices_bb.clear(); - this->idx_bb = 0u; - - this->initializeVertices(); - for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); } - this->update_bb(); - this->reinit_buffers(); - } - - void reserve_vertices (std::size_t n_vertices) - { - this->vertexPositions.reserve (3u * n_vertices); - this->vertexNormals.reserve (3u * n_vertices); - this->vertexColors.reserve (this->ncol * n_vertices); - this->indices.reserve (6u * n_vertices); - } - - // Make a hash of vertexPositions, etc as an identifier for this model. The hash identifies - // the model's mesh geometry for NavMesh and so the vertexColors are not important. - std::size_t hash() const - { - std::size_t h = 17; - for (std::size_t i = 0u; i < this->vertexPositions.size(); ++i) { - h = (h << 5) - 1 + std::hash{}(this->vertexPositions[i]); - } - for (std::size_t i = 0u; i < this->vertexNormals.size(); ++i) { - h = (h << 5) - 1 + std::hash{}(this->vertexNormals[i]); - } - for (std::size_t i = 0u; i < this->indices.size(); ++i) { - h = (h << 5) - 1 + std::hash{}(this->indices[i]); - } - return h; - } - - // Get a single position from vertexPositions, using the index into the vector - // interpretation of vertexPositions - sm::vec get_position (const std::uint32_t vec_idx) const - { - auto vp = reinterpret_cast>*>(&this->vertexPositions); - return (*vp)[vec_idx]; - } - - // Get a single normal from vertexNormals, using the index into the vector - // interpretation of vertexNormals - sm::vec get_normal (const std::uint32_t vec_idx) const - { - auto vn = reinterpret_cast>*>(&this->vertexNormals); - return (*vn)[vec_idx]; - } - - // Get the area of the triangle whose start index is vec_idx - float get_area (const std::uint32_t vec_idx0, const std::uint32_t vec_idx1, const std::uint32_t vec_idx2) const - { - auto vp = reinterpret_cast>*>(&this->vertexPositions); - auto t0 = (*vp)[vec_idx0]; - auto t1 = (*vp)[vec_idx1]; - auto t2 = (*vp)[vec_idx2]; - return sm::geometry::tri_area (t0, t1, t2); - } - - /** - * Neighbour vertex mesh code. - */ - - // Our navigation mesh data struct - std::unique_ptr navmesh; - - void build_navmesh() - { - constexpr bool debug_mn = false; - if constexpr (debug_mn) { std::cout << __func__ << " called" << std::endl; } - - if (!this->navmesh) { return; } - - // Copy the bounding box - navmesh->bb = this->bb; - - // Treat vertexPositions as a vector of vec: - auto vp = reinterpret_cast>*>(&this->vertexPositions); - - std::uint32_t vps = vp->size(); - std::unordered_map, std::set, sm::vec::hash> equiv_v; - std::uint32_t i = 0; - for (auto p : *vp) { equiv_v[p].insert (i++); } - std::map> equiv; - for (auto e : equiv_v) { equiv[*e.second.begin()] = e.second; } - if constexpr (debug_mn) { - for (auto e : equiv) { - std::cout << "build_navmesh: equiv[" << e.first << "] = "; - for (auto idx : e.second) { std::cout << idx << ","; } - std::cout << std::endl; - } - std::cout << "build_navmesh: Populated equiv which has " << equiv.size() << " vvecs" << std::endl; - } - - // Make inverse of equiv to translate from original (indices, vertexPositions) index to - // new topographic mesh index - sm::vvec navmesh_idx (vps, 0); - std::uint32_t vcount = 0; - i = 0; - for (auto eqs : equiv) { - vcount += eqs.second.size(); - for (auto ev : eqs.second) { - if constexpr (debug_mn) { - std::cout << "build_navmesh: set navmesh_idx[" << ev << "] = " << i << std::endl; - } - navmesh_idx[ev] = i; - } - ++i; - } - if constexpr (debug_mn) { std::cout << "build_navmesh: Created equiv inverse" << std::endl; } - - if (vcount != vps) { - std::cout << "build_navmesh: WARNING: Vertex count from equiv is " << vcount - << " which should (but does not) equal " << vps << std::endl; - } - - // Can now populate vertex, a vector of coordinates, if required, or simply access (*vp) - // as needed using equiv.first - navmesh->vertex.resize (equiv.size(), mesh::vertex{}); - i = 0; - for (auto eq : equiv) { - navmesh->vertex[i++] = { (*vp)[eq.first], std::numeric_limits::max() }; - } - - // We're turing a triangle mesh into a navmesh. Don't know what to do if there are stray vertices. - if (this->indices.size() % 3u != 0u) { - throw std::runtime_error ("Uh oh, indices size not divisible by 3!!!! Call the cops!"); - } - - // Lastly, generate edges. For which we require use of indices, which is expressed in - // terms of the old indices. That lookup is navmesh_idx. - for (std::uint32_t i = 0; i < this->indices.size(); i += 3) { - - // Add three halfedges for the triangle - const std::uint32_t hesz = navmesh->halfedge.size(); - const std::uint32_t he0 = hesz; - const std::uint32_t he1 = hesz + 1; - const std::uint32_t he2 = hesz + 2; - - if constexpr (debug_mn) { - std::cout << "setting halfedge["<< he0 << "] to { {" - << navmesh_idx[indices[i]] << ", " << navmesh_idx[indices[i + 1]] - << "}, nullptr, " << he1 << ", " << he2 << " }" << std::endl; - - std::cout << "setting halfedge[" << he1 << "] to { {" - << navmesh_idx[indices[i + 1]] << ", " << navmesh_idx[indices[i + 2]] - << "}, nullptr, " << he2 << ", " << he0 << " }" << std::endl; - - std::cout << "setting halfedge[" << he2 << "] to { {" - << navmesh_idx[indices[i + 2]] << ", " << navmesh_idx[indices[i]] - << "}, nullptr, " << he0 << ", " << he1 << " }" << std::endl; - } - - navmesh->halfedge.resize (hesz + 3, {}); - - // Now, could also try to identify LINES - navmesh->halfedge[he0] = { {navmesh_idx[indices[i ]], navmesh_idx[indices[i + 1]]}, std::numeric_limits::max(), he1, he2, 0u }; - navmesh->halfedge[he1] = { {navmesh_idx[indices[i + 1]], navmesh_idx[indices[i + 2]]}, std::numeric_limits::max(), he2, he0, 0u }; - navmesh->halfedge[he2] = { {navmesh_idx[indices[i + 2]], navmesh_idx[indices[i ]]}, std::numeric_limits::max(), he0, he1, 0u }; - - if constexpr (debug_mn) { - std::cout << "halfedge["<< hesz << "] contains: vi:" - << navmesh->halfedge[hesz].vi - << ", twin:" << navmesh->halfedge[hesz].twin - << ", next:" << navmesh->halfedge[hesz].next - << ", prev:" << navmesh->halfedge[hesz].prev << std::endl; - } - // A face contains just the first half edge index - mesh::face<> t = { he0 }; - - // The normal vector for this triangle could be obtained from the mesh normals, but - // we can't trust them (though they're easy to get, as we're dealing with indices - // already). However, use this to ensure that our triangle indices order is in - // agreement with mesh normal as far as direction goes. - sm::vec tn = this->get_normal (indices[i]) + this->get_normal (indices[i + 1]) + this->get_normal (indices[i + 2]) ; - tn.renormalize(); - - // Compute trinorm as well and compare with the one from the mesh - perhaps it's - // different? We really want the right normal. - const sm::vec& tv0 = navmesh->vertex[navmesh_idx[indices[i]]].p; - const sm::vec& tv1 = navmesh->vertex[navmesh_idx[indices[i + 1]]].p; - const sm::vec& tv2 = navmesh->vertex[navmesh_idx[indices[i + 2]]].p; - sm::vec nx = (tv1 - tv0); - sm::vec ny = (tv2 - tv0); - sm::vec n = nx.cross (ny); - n.renormalize(); - - // Check rotational sense of triangles - if (n.dot (tn) < 0.0f) { - std::cout << "Swap order of triangle with he " << he0 << std::endl; - // Swap first and last half edge - navmesh->halfedge[he0].vi.rotate(); - navmesh->halfedge[he1].vi.rotate(); - navmesh->halfedge[he2].vi.rotate(); - } - navmesh->triangles.push_back (t); - } - if constexpr (debug_mn) { - std::cout << "build_navmesh: Created triangles (" << navmesh->halfedge.size() << " halfedges)" << std::endl; - } - - navmesh->compute_neighbour_relations(); // finds the halfedge twins - } - - /*! - * Post-process vertices to generate a neighbour relationship mesh suitable for navigation. - * - * \param navmesh_dir The directory into which to store/read the navmesh data file. - */ - void make_navmesh (std::string navmesh_dir = "") - { - if (this->navmesh) { return; } // already made it - - if (this->flags.test (vm_bools::compute_bb) == false) { - throw std::runtime_error ("make_navmesh requires compute_bb flag to be true"); - } - this->update_bb(); - - // Create a new navmesh - this->navmesh = std::make_unique(); - - // Have we got a pre-computed navmesh file for the halfedge twin relationships? - std::uint64_t h = this->hash(); - if (navmesh_dir.empty()) { - navmesh_dir = mplot::tools::getTmpPath(); - } else { - if (navmesh_dir.back() != '/') { navmesh_dir += "/"; } - } - std::string filename = navmesh_dir + std::string("navmesh_") + std::to_string (h); - std::string filename_pre_boundary = filename + ".pre"; - - constexpr bool just_mark = true; - if (mplot::tools::fileExists (filename)) { - this->navmesh->load (filename); - std::cout << "Full test...\n"; - this->navmesh->test(); - - } else if (mplot::tools::fileExists (filename_pre_boundary)) { - std::cout << "Pre-boundary navmesh\n"; - this->navmesh->load (filename_pre_boundary); - this->navmesh->add_boundary_halfedges(); - this->navmesh->test (just_mark); - this->navmesh->save (filename); - } else { - std::cout << "Building NavMesh to save into file " << filename << std::endl; - this->build_navmesh(); - this->navmesh->save (filename_pre_boundary); - this->navmesh->add_boundary_halfedges(); - this->navmesh->test (just_mark); - this->navmesh->save (filename); - } - } - - /** - * End neighbour vertex mesh code - */ - - /*! - * A function to call initialiseVertices and postVertexInit after any necessary attributes - * have been set (see, for example, setting the colour maps up in VisualDataModel). - */ - void finalize() - { - mplot::VisualResources::i().setContext (this->parentVis); // need context? yes for text. - this->initializeVertices(); - for (auto mg : this->extra_meshgroups) { this->computeMeshgroup (mg); } - this->update_bb(); - this->flags.set (vm_bools::postVertexInitRequired, true); - // Release context after creating and finalizing this VisualModel. On Visual::render(), - // context will be re-acquired. - mplot::VisualResources::i().releaseContext(); - } - - static constexpr bool debug_render = false; - //! Render the VisualModel. Note that it is assumed that the OpenGL context has been - //! obtained by the parent Visual::render call. - virtual void render() // not final - { - if (this->hidden() == true) { return; } - - // Execute post-vertex init at render, as GL should be available. - if (this->flags.test (vm_bools::postVertexInitRequired) == true) { this->postVertexInit(); } - - std::int32_t prev_shader = 0; - - GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - glfn->GetIntegerv (GL_CURRENT_PROGRAM, &prev_shader); - // Ensure the correct program is in play for this VisualModel - std::uint32_t gprog = mplot::VisualResources::i().get_gprog (this->parentVis); - glfn->UseProgram (gprog); - - if (!this->indices.empty()) { - - // glPolygonMode is OpenGL only and not supported on GL ES - if constexpr (mplot::gl::version::gles (glver) == false) { - // Enable/disable wireframe mode per-model on each render call - if (this->flags.test (vm_bools::wireframe)) { - glfn->PolygonMode (GL_FRONT_AND_BACK, GL_LINE); - } else { - glfn->PolygonMode (GL_FRONT_AND_BACK, GL_FILL); - } - } - - // It is only necessary to bind the vertex array object before rendering - // (not the vertex buffer objects) - glfn->BindVertexArray (this->vao); - - // Pass this->float to GLSL so the model can have an alpha value. - std::int32_t loc_a = glfn->GetUniformLocation (gprog, static_cast("alpha")); - if (loc_a != -1) { glfn->Uniform1f (loc_a, this->alpha); } - - std::int32_t loc_gr = glfn->GetUniformLocation (gprog, static_cast("greyscale")); - if (loc_gr != -1) { glfn->Uniform1i (loc_gr, (this->flags.test (vm_bools::greyscale) ? 1 : 0)); } - - std::int32_t loc_gam = glfn->GetUniformLocation (gprog, static_cast("gamma")); - if (loc_gam != -1) { glfn->Uniform1f (loc_gam, this->gamma); } - - // The scene-view matrix - std::int32_t loc_v = glfn->GetUniformLocation (gprog, static_cast("v_matrix")); - if (loc_v != -1) { glfn->UniformMatrix4fv (loc_v, 1, GL_FALSE, this->scenematrix.arr.data()); } - - // the model-view matrix - std::int32_t loc_m = glfn->GetUniformLocation (gprog, static_cast("m_matrix")); - if (loc_m != -1) { glfn->UniformMatrix4fv (loc_m, 1, GL_FALSE, this->viewmatrix.arr.data()); } - - // the instance scaling matrix (applied to all instances) - std::int32_t loc_s = glfn->GetUniformLocation (gprog, static_cast("s_matrix")); - if (loc_s != -1) { glfn->UniformMatrix4fv (loc_s, 1, GL_FALSE, this->instscale.arr.data()); } - - if constexpr (debug_render) { - std::cout << "VisualModel::render: scenematrix:\n" << this->scenematrix << std::endl; - std::cout << "VisualModel::render: model viewmatrix:\n" << this->viewmatrix << std::endl; - } - - // Draw the triangles - std::int32_t loc_is = glfn->GetUniformLocation (gprog, static_cast("instance_start")); - std::int32_t loc_ic = glfn->GetUniformLocation (gprog, static_cast("instance_count")); - std::int32_t loc_ipc = glfn->GetUniformLocation (gprog, static_cast("instparam_count")); - if (this->flags.test (vm_bools::instanced)) { - if (loc_is != -1) { glfn->Uniform1i (loc_is, this->instance_start); } - if (loc_ic != -1) { glfn->Uniform1i (loc_ic, this->instance_count); } - if (loc_ipc != -1) { glfn->Uniform1i (loc_ipc, this->instparam_count); } - glfn->DrawElementsInstanced (GL_TRIANGLES, static_cast(this->indices.size()), GL_UNSIGNED_INT, 0, this->instance_count); - } else { - if (loc_is != -1) { glfn->Uniform1i (loc_is, -1); } - if (loc_ic != -1) { glfn->Uniform1i (loc_ic, -1); } - glfn->DrawElements (GL_TRIANGLES, static_cast(this->indices.size()), GL_UNSIGNED_INT, 0); - } - - // Unbind the VAO - glfn->BindVertexArray(0); - - // Do the bounding box optionally - if (this->flags.test (vm_bools::compute_bb) && this->flags.test (vm_bools::show_bb) && !this->indices_bb.empty()) { - glfn->BindVertexArray (this->vao_bb); - glfn->DrawElements (GL_TRIANGLES, static_cast(this->indices_bb.size()), GL_UNSIGNED_INT, 0); - glfn->BindVertexArray(0); - } - } - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - - // Now render any VisualTextModels - if constexpr (mplot::gl::version::gles (glver) == false) { - glfn->PolygonMode (GL_FRONT_AND_BACK, GL_FILL); - } - auto ti = this->texts.begin(); - while (ti != this->texts.end()) { (*ti)->render(); ti++; } - - glfn->UseProgram (prev_shader); - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - } - - //! Setter for the viewmatrix - void setViewMatrix (const sm::mat& mv) { this->viewmatrix = mv; } - //! And a getter - sm::mat getViewMatrix() const { return this->viewmatrix; } - //! Pre or post-multiply - void postmultViewMatrix (const sm::mat& m) { this->viewmatrix = this->viewmatrix * m; } - void premultViewMatrix (const sm::mat& m) { this->viewmatrix = m * this->viewmatrix; } - - //! Scale the viewmatrix (this allows you to 'zoom' your model) - void scaleViewMatrix (const float by) { this->viewmatrix.scale (by); } - - //! An alias for scaleViewMatrix - void set_zoom (const float factor) { this->viewmatrix.scale (factor); } - - //! Reflect your model left to right (across the y-z plane through the origin) - void reflect_x() - { - this->postmultViewMatrix (sm::mat::reflection (sm::vec{}, sm::vec::ux())); - } - - //! Reflect your model up/down (across the x-z plane through the origin) - void reflect_y() - { - this->postmultViewMatrix (sm::mat::reflection (sm::vec{}, sm::vec::uy())); - } - - void reflect_z() - { - this->postmultViewMatrix (sm::mat::reflection (sm::vec{}, sm::vec::uz())); - } - - //! When setting the scene matrix, also have to set the text's scene matrices. - void setSceneMatrix (const sm::mat& sv) - { - this->scenematrix = sv; - this->setSceneMatrixTexts (sv); - } - - //! Set a translation into the scene and into any child texts - template requires (N == 3) || (N == 4) - void setSceneTranslation (const sm::vec& v0) - { - this->scenematrix.set_identity(); - this->scenematrix.translate (v0); - if constexpr (N == 4) { - this->setSceneTranslationTexts (v0.less_one_dim()); - } else { - this->setSceneTranslationTexts (v0); - } - } - - //! Set a translation (only) into the scene view matrix - template requires (N == 3) || (N == 4) - void addSceneTranslation (const sm::vec& v0) { this->scenematrix.pretranslate (v0); } - - //! Set a rotation (only) into the scene view matrix - void setSceneRotation (const sm::quaternion& r) - { - this->scenematrix.set_identity(); - this->scenematrix.rotate (r); - } - - //! Add a rotation to the scene view matrix - void addSceneRotation (const sm::quaternion& r) { this->scenematrix.rotate (r); } - - //! Set a translation to the model view matrix - template requires (N == 3) || (N == 4) - void setViewTranslation (const sm::vec& v0) - { - this->viewmatrix.set_identity(); - this->viewmatrix.translate (v0); - } - - //! Add a translation to the model view matrix - template requires (N == 3) || (N == 4) - void addViewTranslation (const sm::vec& v0) { this->viewmatrix.pretranslate (v0); } - - //! Set a rotation (only) into the view, but keep texts fixed - void setViewRotationFixTexts (const sm::quaternion& r) - { - sm::vec<> os = this->viewmatrix.translation(); - this->viewmatrix.set_identity(); - this->viewmatrix.translate (os); - this->viewmatrix.rotate (r); - } - - //! Set a rotation (only) into the view - void setViewRotation (const sm::quaternion& r) - { - sm::vec<> os = this->viewmatrix.translation(); - this->viewmatrix.set_identity(); - this->viewmatrix.translate (os); - this->viewmatrix.rotate (r); - this->setViewRotationTexts (r); - } - - //! Apply a further rotation to the model view matrix - void addViewRotation (const sm::quaternion& r) - { - this->viewmatrix.rotate (r); - this->addViewRotationTexts (r); - } - - //! Apply a further rotation to the model view matrix, but keep texts fixed - void addViewRotationFixTexts (const sm::quaternion& r) - { - this->viewmatrix.rotate (r); - } - - // The alpha attribute accessors - void setAlpha (const float _a) { this->alpha = _a; } - float getAlpha() const { return this->alpha; } - void incAlpha() - { - this->alpha += 0.1f; - this->alpha = this->alpha > 1.0f ? 1.0f : this->alpha; - } - void decAlpha() - { - this->alpha -= 0.1f; - this->alpha = this->alpha < 0.0f ? 0.0f : this->alpha; - } - - void setGamma (const float _g) { this->gamma = _g; } - float getGamma () const { return this->gamma; } - - // The hide attribute accessors - void setHide (const bool _h = true) { this->flags.set (vm_bools::hide, _h); } - void toggleHide() { this->flags.flip (vm_bools::hide); } - bool hidden() const { return this->flags.test (vm_bools::hide); } - - /* - * Methods used by Visual::savegltf() - */ - - //! Get model translation in a json-friendly string - std::string translation_str() { return this->viewmatrix.translation().str_mat(); } - //! A getter for the viewmatrix translation of the origin (would be same as viewmatrix.translation) - sm::vec get_viewmatrix_origin() const - { - return (this->viewmatrix * sm::vec{0,0,0}).less_one_dim(); - } - - //! The centre of mass of the bounding box may not be the VisualModel's origin - sm::vec get_viewmatrix_bb_centre() const - { - return (this->viewmatrix * this->bb.mid()).less_one_dim(); - } - - //! Apply the viewmatrix to the model's bounding box and return it. You probably don't want - //! this, instead, get_viewmatrix_obb gets the oriented bounding box, and with that you can - //! collision detect with the separarating axis theorem. - sm::interval> get_viewmatrix_modelbb() const - { - sm::interval> vmbb; - vmbb.min = (this->viewmatrix * this->bb.min).less_one_dim(); - vmbb.max = (this->viewmatrix * this->bb.max).less_one_dim(); - return vmbb; - } - - /*! - * Returns a 3x4 matrix whose columns are the vectors obb_centre, obb_x, obb_y and obb_z - * (the half-extent vectors) for the axis aligned bounding box *after* it has been - * transformed (oriented) with the passed in @_viewmatrix. - * - * The returned mat can be passed to Visual::collision_detect(obb1, obb2) - */ - sm::mat get_viewmatrix_obb (const sm::mat& _viewmatrix) const - { - const sm::vec bb_centre = this->bb.mid(); - const sm::vec obb_x_end = (_viewmatrix * (bb_centre + this->bb_x)).less_one_dim(); - const sm::vec obb_y_end = (_viewmatrix * (bb_centre + this->bb_y)).less_one_dim(); - const sm::vec obb_z_end = (_viewmatrix * (bb_centre + this->bb_z)).less_one_dim(); - const sm::vec obb_centre = (_viewmatrix * bb_centre).less_one_dim(); - sm::mat obb; - obb.set_col (0, obb_centre); - obb.set_col (1, obb_x_end - obb_centre); - obb.set_col (2, obb_y_end - obb_centre); - obb.set_col (3, obb_z_end - obb_centre); - return obb; - } - - /*! - * Returns a 3x4 matrix whose columns are the vectors obb_centre, obb_x, obb_y and obb_z for - * the axis aligned bounding box *after* it has been oriented with this model's viewmatrix. - */ - sm::mat get_viewmatrix_obb() const { return this->get_viewmatrix_obb (this->viewmatrix); } - - /*! - * Find collision between this model's oriented bounding box and another oriented bounding box. - */ - bool collision_detect (const sm::mat& obb2) - { - const sm::mat obb1 = this->get_viewmatrix_obb (this->viewmatrix); - return sm::geometry::obb_collision_detect(obb1, obb2); - } - - /*! - * Find collision between this model's oriented bounding box and another model. - */ - bool collision_detect (const VisualModel* mdl2) - { - const sm::mat obb1 = this->get_viewmatrix_obb (this->viewmatrix); - const sm::mat obb2 = mdl2->get_viewmatrix_obb(); - return sm::geometry::obb_collision_detect(obb1, obb2); - } - - //! Return the number of elements in this->indices - std::size_t indices_size() { return this->indices.size(); } - float indices_max() { return this->idx_max; } - float indices_min() { return this->idx_min; } - std::size_t indices_bytes() { return this->indices.size() * sizeof (std::uint32_t); } - //! Return base64 encoded version of indices - std::string indices_base64() - { - std::vector idx_bytes (this->indices.size() << 2, 0); - std::size_t b = 0u; - for (auto i : this->indices) { - idx_bytes[b++] = i & 0xff; - idx_bytes[b++] = i >> 8 & 0xff; - idx_bytes[b++] = i >> 16 & 0xff; - idx_bytes[b++] = i >> 24 & 0xff; - } - return sm::base64::encode (idx_bytes); - } - - /*! - * Find the extents of this VisualModel, returning it as the x range, the y range and the z range. - */ - sm::vec, 3> extents() - { - sm::vec, 3> axis_extents; - for (std::uint32_t i = 0; i < 3; ++i) { axis_extents[i].search_init(); } - for (std::uint32_t j = 0; j < static_cast(this->vertexPositions.size() - 2); j += 3) { - for (std::uint32_t i = 0; i < 3; ++i) { axis_extents[i].update (this->vertexPositions[j+i]); } - } - return axis_extents; - } - - /*! - * Compute the max and min values of indices and vertexPositions/Colors/Normals for use - * when saving gltf files - */ - void computeVertexMaxMins() - { - // Compute index maxmins - for (std::size_t i = 0u; i < this->indices.size(); ++i) { - idx_max = this->indices[i] > idx_max ? this->indices[i] : idx_max; - idx_min = this->indices[i] < idx_min ? this->indices[i] : idx_min; - } - // Check every 0th entry in vertex Positions, every 1st, etc for max in the - - if (this->vertexPositions.size() != this->vertexColors.size() - ||this->vertexPositions.size() != this->vertexNormals.size()) { - throw std::runtime_error ("Expect vertexPositions, Colors and Normals vectors all to have same size"); - } - - for (std::size_t i = 0u; i < this->vertexPositions.size(); i += 3u) { - vpos_maxes[0] = (vertexPositions[i] > vpos_maxes[0]) ? vertexPositions[i] : vpos_maxes[0]; - vpos_maxes[1] = (vertexPositions[i+1] > vpos_maxes[1]) ? vertexPositions[i+1] : vpos_maxes[1]; - vpos_maxes[2] = (vertexPositions[i+2] > vpos_maxes[2]) ? vertexPositions[i+2] : vpos_maxes[2]; - vnorm_maxes[0] = (vertexNormals[i] > vnorm_maxes[0]) ? vertexNormals[i] : vnorm_maxes[0]; - vnorm_maxes[1] = (vertexNormals[i+1] > vnorm_maxes[1]) ? vertexNormals[i+1] : vnorm_maxes[1]; - vnorm_maxes[2] = (vertexNormals[i+2] > vnorm_maxes[2]) ? vertexNormals[i+2] : vnorm_maxes[2]; - - vpos_mins[0] = (vertexPositions[i] < vpos_mins[0]) ? vertexPositions[i] : vpos_mins[0]; - vpos_mins[1] = (vertexPositions[i+1] < vpos_mins[1]) ? vertexPositions[i+1] : vpos_mins[1]; - vpos_mins[2] = (vertexPositions[i+2] < vpos_mins[2]) ? vertexPositions[i+2] : vpos_mins[2]; - vnorm_mins[0] = (vertexNormals[i] < vnorm_mins[0]) ? vertexNormals[i] : vnorm_mins[0]; - vnorm_mins[1] = (vertexNormals[i+1] < vnorm_mins[1]) ? vertexNormals[i+1] : vnorm_mins[1]; - vnorm_mins[2] = (vertexNormals[i+2] < vnorm_mins[2]) ? vertexNormals[i+2] : vnorm_mins[2]; - } - for (std::size_t i = 0u; i < this->vertexPositions.size(); i += this->ncol) { - vcol_maxes[0] = (vertexColors[i] > vcol_maxes[0]) ? vertexColors[i] : vcol_maxes[0]; - vcol_maxes[1] = (vertexColors[i+1] > vcol_maxes[1]) ? vertexColors[i+1] : vcol_maxes[1]; - vcol_maxes[2] = (vertexColors[i+2] > vcol_maxes[2]) ? vertexColors[i+2] : vcol_maxes[2]; - vcol_mins[0] = (vertexColors[i] < vcol_mins[0]) ? vertexColors[i] : vcol_mins[0]; - vcol_mins[1] = (vertexColors[i+1] < vcol_mins[1]) ? vertexColors[i+1] : vcol_mins[1]; - vcol_mins[2] = (vertexColors[i+2] < vcol_mins[2]) ? vertexColors[i+2] : vcol_mins[2]; - } - } - - std::size_t vpos_size() { return this->vertexPositions.size(); } - std::string vpos_max() { return this->vpos_maxes.str_mat(); } - std::string vpos_min() { return this->vpos_mins.str_mat(); } - std::size_t vpos_bytes() { return this->vertexPositions.size() * sizeof (float); } - std::string vpos_base64() - { - std::vector _bytes (this->vertexPositions.size() << 2, 0); - std::size_t b = 0u; - float_bytes fb; - for (auto i : this->vertexPositions) { - fb.f = i; - _bytes[b++] = fb.bytes[0]; - _bytes[b++] = fb.bytes[1]; - _bytes[b++] = fb.bytes[2]; - _bytes[b++] = fb.bytes[3]; - } - return sm::base64::encode (_bytes); - } - std::size_t next_vpos_idx = 0; - void init_vpos_accessor() { this->next_vpos_idx = 0; } - sm::vec get_next_vpos() - { - sm::vec pos; - pos.set_from (std::numeric_limits::max()); - if (this->next_vpos_idx < this->vertexPositions.size()) { - sm::vec tmp = { - this->vertexPositions[this->next_vpos_idx], - this->vertexPositions[this->next_vpos_idx + 1], - this->vertexPositions[this->next_vpos_idx + 2] - }; - - pos = (this->viewmatrix * tmp).less_one_dim(); - this->next_vpos_idx += 3; - } - return pos; - } - - std::size_t vcol_size() { return this->vertexColors.size(); } - std::string vcol_max() { return this->vcol_maxes.str_mat(); } - std::string vcol_min() { return this->vcol_mins.str_mat(); } - std::size_t vcol_bytes() { return this->vertexColors.size() * sizeof (float); } - std::string vcol_base64() - { - std::vector _bytes (this->vertexColors.size() << 2, 0); - std::size_t b = 0u; - float_bytes fb; - for (auto i : this->vertexColors) { - fb.f = i; - _bytes[b++] = fb.bytes[0]; - _bytes[b++] = fb.bytes[1]; - _bytes[b++] = fb.bytes[2]; - _bytes[b++] = fb.bytes[3]; - } - return sm::base64::encode (_bytes); - } - std::size_t vnorm_size() { return this->vertexNormals.size(); } - std::string vnorm_max() { return this->vnorm_maxes.str_mat(); } - std::string vnorm_min() { return this->vnorm_mins.str_mat(); } - std::size_t vnorm_bytes() { return this->vertexNormals.size() * sizeof (float); } - std::string vnorm_base64() - { - std::vector _bytes (this->vertexNormals.size()<<2, 0); - std::size_t b = 0u; - float_bytes fb; - for (auto i : this->vertexNormals) { - fb.f = i; - _bytes[b++] = fb.bytes[0]; - _bytes[b++] = fb.bytes[1]; - _bytes[b++] = fb.bytes[2]; - _bytes[b++] = fb.bytes[3]; - } - return sm::base64::encode (_bytes); - } - std::size_t next_vnorm_idx = 0; - void init_vnorm_accessor() { this->next_vnorm_idx = 0; } - sm::vec get_next_vnorm() - { - sm::vec pos; - pos.set_from (std::numeric_limits::max()); - if (this->next_vnorm_idx < this->vertexPositions.size()) { - pos = { this->vertexPositions[this->next_vnorm_idx], - this->vertexPositions[this->next_vnorm_idx + 1], - this->vertexPositions[this->next_vnorm_idx + 2] }; - this->next_vnorm_idx += 3; - } - return pos; - } - // end Visual::savegltf() methods - - // A VisualModel may be given a name - std::string name = {}; - - //! The current indices index - std::uint32_t idx = 0u; - std::uint32_t idx_bb = 0u; - - /*! - * This is the upper limit for instance_count. We reserve max_isntances of space in the SSBO. - * - * Max number of instances in a model. Each *model* has to reserve space in the SSBOs which - * are managed by VisualResources. VisualResources::max_instances must be larger than this. - */ - std::uint32_t max_instances = 16 * 1024; - //! The offset into the SSBOs for the instance data for this VisualModel - std::uint32_t instance_start = 0; - //! If drawing with instancing, how many instances? <= this->max_instances - std::uint32_t instance_count = 0; - //! If drawing with instancing, how many params will be used (these will be cycled through - //! per-instance and there may be fewer than instance_count parameters) - std::uint32_t instparam_count = 0; - - //! Set the scaling matrix for all instances - void set_instance_scale (const float scl) - { - this->instscale.set_identity(); - this->instscale.scale (scl); - } - - //! Set up the instance positions (with default params for colour, rotn, scale) - void set_instance_data (const sm::vvec>& position) - { - sm::vvec> c = { this->instcolour }; - sm::vvec a = { 1.0f }; - sm::vvec s = { 1.0f }; - this->set_instance_data (position, c, a, s); - } - - //! Set instance positions, with an array containing colour, alpha and scale values to apply - //! to the instances. The size of colour, alpha and scale must match, but it may be of a - //! different size to position. - void set_instance_data (const sm::vvec>& position, const std::array& colour, - const float alpha = 1.0f, const float scale = 1.0f) - { - sm::vvec> c = { colour }; - sm::vvec a = { alpha }; - sm::vvec s = { scale }; - this->set_instance_data (position, c, a, s); - } - - //! Set up the instance positions and params (colour, alpha, scale). Add rotation later on. - void set_instance_data (const sm::vvec>& position, - const sm::vvec>& colour, - const sm::vvec& alpha, const sm::vvec& scale) - { - if (position.size() < 1) { - // Clear data - this->instance_count = 0; - this->instparam_count = 0; - mplot::VisualResources::i().instanced_needs_update (this->parentVis); - return; - } - if (position.size() > this->max_instances) { - std::string ee1 = "set_instance_data: Haven't reserved enough space for that. position.size() = "; - std::string ee2 = std::to_string (position.size()); - std::string ee3 = " > max_instances = "; - std::string ee4 = std::to_string (max_instances); - throw std::runtime_error (ee1 + ee2 + ee3 + ee4); - } - if (colour.size() != scale.size() || colour.size() != alpha.size()) { - throw std::runtime_error ("set_instance_data: params vvecs should all have same size (colour, rotn, scale)"); - } - - for (std::size_t i = 0; i < position.size(); ++i) { - // Get access to the SSBO in VisualResources and add the 3 floats in position[i] at - // the location defined by this->instance_start + i - mplot::VisualResources::i().insert_instance_data (this->instance_start + i, position[i]); - } - this->instance_count = position.size(); - - for (std::size_t i = 0; i < colour.size(); ++i) { - mplot::VisualResources::i().insert_instparam_data (this->instance_start + i, colour[i], alpha[i], scale[i]); - } - this->instparam_count = colour.size(); - - mplot::VisualResources::i().instanced_needs_update (this->parentVis); - } - - //! Setter for the parent ID, parentVis - void set_parent (const std::uint32_t _vis) - { - if (this->parentVis == std::numeric_limits::max()) { this->parentVis = _vis; } - } - - // Flags defaults. - constexpr sm::flags flags_defaults() - { - sm::flags _flags; - _flags.set (vm_bools::postVertexInitRequired, false); - _flags.set (vm_bools::twodimensional, false); - _flags.set (vm_bools::hide, false); - _flags.set (vm_bools::wireframe, false); - _flags.set (vm_bools::greyscale, false); - _flags.set (vm_bools::show_bb, false); - _flags.set (vm_bools::compute_bb, true); - return _flags; - } - - // State/options flags - sm::flags flags = flags_defaults(); - - // Setters for flags - void show_bb (const bool val) { this->flags.set (vm_bools::show_bb, val); } - void compute_bb (const bool val) { this->flags.set (vm_bools::compute_bb, val); } - - /*! - * An interval can be used for an axis-aligned bounding box for this VisualModel. You can - * get the centre with bb.mid(). - */ - sm::interval> bb; - std::array colour_bb = mplot::colour::grey90; - // Bounding box half-extent vectors (which can be converted into an oriented bb with the viewmatrix) - sm::vec bb_x = {}; - sm::vec bb_y = {}; - sm::vec bb_z = {}; - - void twodimensional (const bool val) { this->flags.set (vm_bools::twodimensional, val); } - bool twodimensional() const { return this->flags.test (vm_bools::twodimensional); } - - // Wireframe rendering is not aviailable on GL ES - template requires (mplot::gl::version::gles (glver) == false) - void wireframe (const bool val) { this->flags.set (vm_bools::wireframe, val); } - template requires (mplot::gl::version::gles (glver) == false) - bool wireframe() const { return this->flags.test (vm_bools::wireframe); } - - void greyscale (const bool val) { this->flags.set (vm_bools::greyscale, val); } - bool greyscale() const { return this->flags.test (vm_bools::greyscale); } - - void instanced (const bool val) { this->flags.set (vm_bools::instanced, val); } - bool instanced() const { return this->flags.test (vm_bools::instanced); } - - //! Getter for vertex positions (for mplot::NormalsVisual) - std::vector getVertexPositions() { return this->vertexPositions; } - //! Getter for vertex normals (for mplot::NormalsVisual) - std::vector getVertexNormals() { return this->vertexNormals; } - std::vector getVertexColors() { return this->vertexColors; } - - // A vector of meshgroups to be appended to the end of this VisualModel. The vertices in - // these meshgroups are added after the call to initializeVertices. - std::vector extra_meshgroups; - - // Add a meshgroup by pointer. These are appended at the end of initializeVertices - void addMeshgroup (const mplot::meshgroup& mg) { this->extra_meshgroups.push_back (mg); } - - protected: - - //! The model-specific view matrix. Used to transform the pose of the model in the scene. - sm::mat viewmatrix = sm::mat::identity(); - /*! - * The scene view matrix. Each VisualModel has a copy of the scenematrix. It's set in - * Visual::render. Different VisualModels may have different scenematrices (for example, the - * CoordArrows has a different scenematrix from other VisualModels, and models marked - * 'twodimensional' also have a different scenematrix). - */ - sm::mat scenematrix = sm::mat::identity(); - - /*! - * Instance scaling. This matrix can be used to control the scale of all instances of an - * instanced VisualModel - */ - sm::mat instscale = sm::mat::identity(); - - /*! - * The colour for all instances. This is used if you don't set colour in your instance params. - */ - std::array instcolour = mplot::colour::yellow; - - //! Contains the positions within the vbo array of the different vertex buffer objects - enum VBOPos { posnVBO, normVBO, colVBO, idxVBO, numVBO }; - - /* - * Compute positions and colours of vertices for the hexes and store in these: - */ - - //! The OpenGL Vertex Array Object - std::uint32_t vao = 0; - - //! Vertex Buffer Objects stored in an array - std::unique_ptr vbos; - - //! CPU-side data for indices - std::vector indices = {}; - //! CPU-side data for vertex positions - std::vector vertexPositions = {}; - //! CPU-side data for vertex normals - std::vector vertexNormals = {}; - //! CPU-side data for vertex colours - std::vector vertexColors = {}; - - //! Number of elements in a colour (if 4, then last element is alpha) - std::uint32_t ncol = 3; - - // OpenGL arrays for the bounding box, if needed - std::uint32_t vao_bb = 0; - std::unique_ptr vbos_bb; - std::vector indices_bb = {}; - std::vector vpos_bb = {}; - std::vector vnorm_bb = {}; - std::vector vcol_bb = {}; - - static constexpr float _max = std::numeric_limits::max(); - static constexpr float _low = std::numeric_limits::lowest(); - - // The max and min values in the next 8 attributes are only computed if gltf files are going - // to be output by Visual::savegltf() - - //! Max values of 0th, 1st and 2nd coordinates in vertexPositions - sm::vec vpos_maxes = { _low, _low, _low }; // fixme: same as bounding box! - //! Min values in vertexPositions - sm::vec vpos_mins = { _max, _max, _max }; - sm::vec vcol_maxes = { _low, _low, _low }; - sm::vec vcol_mins = { _max, _max, _max }; - sm::vec vnorm_maxes = { _low, _low, _low }; - sm::vec vnorm_mins = { _max, _max, _max }; - //! Max value in indices - std::uint32_t idx_max = 0u; - //! Min value in indices. - std::uint32_t idx_min = std::numeric_limits::max(); - - //! A model-wide alpha value for the shader - float alpha = 1.0f; - - //! A per-model gamma value to interpret the colours in the model. Applied in the vertex shader. - float gamma = 1.0f; - - // The mplot::VisualBase in which this model exists. - std::uint32_t parentVis = std::numeric_limits::max(); - - //! A vector of pointers to text models that should be rendered. - std::vector>> texts; - - //! Set up a vertex buffer object - bind, buffer and set vertex array object - //! attribute. n_dims = 3 for position, normal, 3 or 4 for colour. - void setupVBO (std::uint32_t& buf, std::vector& dat, std::uint32_t bufferAttribPosition, std::uint32_t n_dims) - { - std::size_t sz = dat.size() * sizeof(float); - - if (this->parentVis == std::numeric_limits::max()) { - throw std::runtime_error ("parentVis is unset"); - } - GladGLContext* glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - glfn->BindBuffer (GL_ARRAY_BUFFER, buf); - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - glfn->BufferData (GL_ARRAY_BUFFER, sz, dat.data(), GL_STATIC_DRAW); - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - glfn->VertexAttribPointer (bufferAttribPosition, n_dims, GL_FLOAT, GL_FALSE, 0, (void*)(0)); - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - glfn->EnableVertexAttribArray (bufferAttribPosition); - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - } - - //! Push three floats onto the vector of floats \a vp - void vertex_push (const float& x, const float& y, const float& z, std::vector& vp) - { - vp.emplace_back (x); - vp.emplace_back (y); - vp.emplace_back (z); - } - //! Push four floats onto the vector of floats \a vp - void vertex_push (const float& x, const float& y, const float& z, const float& w, std::vector& vp) - { - vp.emplace_back (x); - vp.emplace_back (y); - vp.emplace_back (z); - vp.emplace_back (w); - } - //! Push array of 3 floats onto the vector of floats \a vp N is the number of dimensions in - //! the passed in normal or position arr, but only 3 are ever stored. - template requires (N == 3 || N == 4) - void vertex_push (const std::array& arr, std::vector& vp) - { - vp.emplace_back (arr[0]); - vp.emplace_back (arr[1]); - vp.emplace_back (arr[2]); - // Ignore any fourth element - } - //! Push sm::vec of 3 floats onto the vector of floats \a vp - template requires (N == 3 || N == 4) - void vertex_push (const sm::vec& vec, std::vector& vp) - { - vp.emplace_back (vec[0]); - vp.emplace_back (vec[1]); - vp.emplace_back (vec[2]); - // Ignore any fourth element - } - template requires (N == 3 || N == 4) - void vertex_push_colour (const std::array& arr, std::vector& vp) - { - vp.emplace_back (arr[0]); - vp.emplace_back (arr[1]); - vp.emplace_back (arr[2]); - // For colour, fourth element may be alpha - if (this->ncol == 4) { - if constexpr (N == 4) { - vp.emplace_back (arr[3]); - } else { - vp.emplace_back (1.0f); - } - } - } - //! Push sm::vec of 3 floats onto the vector of floats \a vp - template requires (N == 3 || N == 4) - void vertex_push_colour (const sm::vec& vec, std::vector& vp) - { - vp.emplace_back (vec[0]); - vp.emplace_back (vec[1]); - vp.emplace_back (vec[2]); - if (this->ncol == 4) { - if constexpr (N == 4) { - vp.emplace_back (vec[3]); - } else { - vp.emplace_back (1.0f); - } - } - } - - /*! - * Add the given meshgroup to this VisualModel - */ - void computeMeshgroup (const mplot::meshgroup& mg) - { - mg.validate(); - - bool single_colr = mg.colours.empty(); - for (std::uint32_t i = 0; i < mg.positions.size(); ++i) { - // We apply mg.transform *here*, rather than writing it into the viewmatrix. This is - // because other elements of this visual model may be added with the assumption of an - // identity viewmatrix. - this->vertex_push (mg.transform * mg.positions[i], this->vertexPositions); - this->vertex_push (mg.transform * mg.normals[i], this->vertexNormals); - if (single_colr) { - this->vertex_push_colour (mg.single_colour, this->vertexColors); - } else { - this->vertex_push_colour (mg.colours[i], this->vertexColors); - } - } - for (std::uint32_t i = 0; i < mg.indices.size(); ++i) { - this->indices.push_back (mg.indices[i] + this->idx); - } - this->idx += mg.positions.size(); - } - - /** - * START vertex/index computation code - * - * ALL methods below this point are for computing vertices. - * - * The metheds compute vertexPositions/Normals/Colors along with indices in a form suitable - * for use with GL's DrawElements (or DrawElementsInstanced) drawing call. - */ - - /*! - * Create a tube from \a start to \a end, with radius \a r and a colour which - * transitions from the colour \a colStart to \a colEnd. - * - * This version simply sub-calls into computeFlaredTube which will randomly choose the angle - * of the vertices around the centre of each end cap. - * - * \param idx The index into the 'vertex array' - * \param start The start of the tube - * \param end The end of the tube - * \param colStart The tube starting colour - * \param colEnd The tube's ending colour - * \param r Radius of the tube - * \param segments Number of segments used to render the tube - */ - void computeTube (sm::vec start, sm::vec end, - std::array colStart, std::array colEnd, - float r = 1.0f, std::int32_t segments = 12) - { - this->computeFlaredTube (start, end, colStart, colEnd, r, r, segments); - } - - /*! - * Compute a tube. This version requires unit vectors for orientation of the - * tube end faces/vertices (useful for graph markers). The other version uses a - * randomly chosen vector to do this. - * - * Create a tube from \a start to \a end, with radius \a r and a colour which - * transitions from the colour \a colStart to \a colEnd. - * - * \param start The start of the tube - * \param end The end of the tube - * \param _ux a vector in the x axis direction for the end face - * \param _uy a vector in the y axis direction. _ux ^ _uy gives the end cap normal - * \param colStart The tube starting colour - * \param colEnd The tube's ending colour - * \param r Radius of the tube - * \param segments Number of segments used to render the tube - * \param rotation A rotation in the _ux/_uy plane to orient the vertices of the - * tube. Useful if this is to be a short tube used as a graph marker. - * \param bb If true, write into the bounding box arrays, not the main ones - */ - void computeTube (sm::vec start, sm::vec end, - sm::vec _ux, sm::vec _uy, - std::array colStart, std::array colEnd, - float r = 1.0f, std::int32_t segments = 12, float rotation = 0.0f, bool bb = false) - { - // The vector from start to end defines direction of the tube - sm::vec vstart = start; - sm::vec vend = end; - - // v is a face normal - sm::vec v = _ux.cross(_uy); - v.renormalize(); - - // If bounding box, populate different buffers: - std::vector& vp = bb ? this->vpos_bb : this->vertexPositions; - std::vector& vn = bb ? this->vnorm_bb : this->vertexNormals; - std::vector& vc = bb ? this->vcol_bb : this->vertexColors; - std::vector& idcs = bb ? this->indices_bb : this->indices; - std::uint32_t& _idx = bb ? this->idx_bb : this->idx; - - // Push the central point of the start cap - this is at location vstart - this->vertex_push (vstart, vp); - this->vertex_push (-v, vn); - this->vertex_push_colour (colStart, vc); - - // Start cap vertices (a triangle fan) - for (std::int32_t j = 0; j < segments; j++) { - // t is the angle of the segment - float t = rotation + j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; - this->vertex_push (vstart+c, vp); - this->vertex_push (-v, vn); - this->vertex_push_colour (colStart, vc); - } - - // Intermediate, near start cap. Normals point in direction c - for (std::int32_t j = 0; j < segments; j++) { - float t = rotation + j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; - this->vertex_push (vstart+c, vp); - c.renormalize(); - this->vertex_push (c, vn); - this->vertex_push_colour (colStart, vc); - } - - // Intermediate, near end cap. Normals point in direction c - for (std::int32_t j = 0; j < segments; j++) { - float t = rotation + (float)j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; - this->vertex_push (vend+c, vp); - c.renormalize(); - this->vertex_push (c, vn); - this->vertex_push_colour (colEnd, vc); - } - - // Bottom cap vertices - for (std::int32_t j = 0; j < segments; j++) { - float t = rotation + (float)j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; - this->vertex_push (vend+c, vp); - this->vertex_push (v, vn); - this->vertex_push_colour (colEnd, vc); - } - - // Bottom cap. Push centre vertex as the last vertex. - this->vertex_push (vend, vp); - this->vertex_push (v, vn); - this->vertex_push_colour (colEnd, vc); - - // Number of vertices = segments * 4 + 2. - std::int32_t nverts = (segments * 4) + 2; - - // After creating vertices, push all the indices. - std::uint32_t capMiddle = _idx; - std::uint32_t capStartIdx = _idx + 1u; - std::uint32_t endMiddle = _idx + static_cast(nverts) - 1u; - std::uint32_t endStartIdx = capStartIdx + (3u * segments); - - // Start cap indices - for (std::int32_t j = 0; j < segments-1; j++) { - idcs.push_back (capMiddle); - idcs.push_back (capStartIdx + j); - idcs.push_back (capStartIdx + 1 + j); - } - // Last one - idcs.push_back (capMiddle); - idcs.push_back (capStartIdx + segments - 1); - idcs.push_back (capStartIdx); - - // Middle sections - for (std::int32_t lsection = 0; lsection < 3; ++lsection) { - capStartIdx = _idx + 1 + lsection*segments; - endStartIdx = capStartIdx + segments; - for (std::int32_t j = 0; j < segments; j++) { - idcs.push_back (capStartIdx + j); - if (j == (segments-1)) { - idcs.push_back (capStartIdx); - } else { - idcs.push_back (capStartIdx + 1 + j); - } - idcs.push_back (endStartIdx + j); - idcs.push_back (endStartIdx + j); - if (j == (segments-1)) { - idcs.push_back (endStartIdx); - } else { - idcs.push_back (endStartIdx + 1 + j); - } - if (j == (segments-1)) { - idcs.push_back (capStartIdx); - } else { - idcs.push_back (capStartIdx + j + 1); - } - } - } - - // bottom cap - for (std::int32_t j = 0; j < segments-1; j++) { - idcs.push_back (endMiddle); - idcs.push_back (endStartIdx + j); - idcs.push_back (endStartIdx + 1 + j); - } - idcs.push_back (endMiddle); - idcs.push_back (endStartIdx + segments - 1); - idcs.push_back (endStartIdx); - - // Update idx - _idx += nverts; - } // end computeTube with ux/uy vectors for faces - - /*! - * A 'draw an arrow' primitive. This is a 3D, tubular arrow made of a tube and a cone. - * - * \param start Start coordinate of the arrow - * - * \param end End coordinate of the arrow - * - * \param clr The colour for the arrow - * - * \param tube_radius Radius of arrow shaft. If < 0, then set from (end-start).length() - * - * \param arrowhead_prop The proportion of the arrow length that the head should take up - * - * \param cone_radius Radisu of cone that make the arrow head. If < 0, then set from - * tube_radius - * - * \param shapesides How many facets to draw tube/cone with - */ - void computeArrow (const sm::vec& start, const sm::vec& end, - const std::array clr, - float tube_radius = -1.0f, - float arrowhead_prop = -1.0f, - float cone_radius = -1.0f, - const std::int32_t shapesides = 18) - { - // The right way to draw an arrow. - sm::vec arrow_line = end - start; - float len = arrow_line.length(); - // Unless client code specifies, compute tube radius from length of arrow - if (tube_radius < 0.0f) { tube_radius = len / 40.0f; } - if (arrowhead_prop < 0.0f) { arrowhead_prop = 0.15f; } - if (cone_radius < 0.0f) { cone_radius = 1.75f * tube_radius; } - // We don't draw the full tube - sm::vec cone_start = arrow_line.shorten (len * arrowhead_prop); - cone_start += start; - this->computeTube (start, cone_start, clr, clr, tube_radius, shapesides); - float conelen = (end-cone_start).length(); - if (arrow_line.length() > conelen) { - this->computeCone (cone_start, end, 0.0f, clr, cone_radius, shapesides); - } - } - - /*! - * Create a flared tube from \a start to \a end, with radius \a r at the start and a colour - * which transitions from the colour \a colStart to \a colEnd. The radius of the end is - * determined by the given angle, flare, in radians. - * - * \param idx The index into the 'vertex array' - * \param start The start of the tube - * \param end The end of the tube - * \param colStart The tube starting colour - * \param colEnd The tube's ending colour - * \param r Radius of the tube - * \param segments Number of segments used to render the tube - * \param flare The angle, measured wrt the direction of the tube in radians, by which the - * tube 'flares' - */ - void computeFlaredTube (sm::vec start, sm::vec end, - std::array colStart, std::array colEnd, - float r = 1.0f, std::int32_t segments = 12, float flare = 0.0f) - { - // Find the length of the tube - sm::vec v = end - start; - float l = v.length(); - // Compute end radius from the length and the flare angle: - float r_add = l * std::tan (std::abs(flare)) * (flare > 0.0f ? 1.0f : -1.0f); - float r_end = r + r_add; - // Now call into the other overload: - this->computeFlaredTube (start, end, colStart, colEnd, r, r_end, segments); - } - - /*! - * Create a flared tube from \a start to \a end, with radius \a r at the start and a colour - * which transitions from the colour \a colStart to \a colEnd. The radius of the end is - * r_end, given as a function argument. - * - * \param start The start of the tube - * \param end The end of the tube - * \param colStart The tube starting colour - * \param colEnd The tube's ending colour - * \param r Radius of the tube's start cap - * \param r_end radius of the end cap - * \param segments Number of segments used to render the tube - */ - void computeFlaredTube (sm::vec start, sm::vec end, - std::array colStart, std::array colEnd, - float r = 1.0f, float r_end = 1.0f, std::int32_t segments = 12) - { - // The vector from start to end defines a vector and a plane. Find a - // 'circle' of points in that plane. - sm::vec vstart = start; - sm::vec vend = end; - sm::vec v = vend - vstart; - v.renormalize(); - - // circle in a plane defined by a point (v0 = vstart or vend) and a normal - // (v) can be found: Choose random vector vr. A vector inplane = vr ^ v. The - // unit in-plane vector is inplane.normalise. Can now use that vector in the - // plan to define a point on the circle. Note that this starting point on - // the circle is at a random position, which means that this version of - // computeTube is useful for tubes that have quite a few segments. - sm::vec rand_vec; - rand_vec.randomize(); - sm::vec inplane = rand_vec.cross(v); - inplane.renormalize(); - - // Now use parameterization of circle inplane = p1-x1 and - // c1(t) = ( (p1-x1).normalized std::sin(t) + v.normalized cross (p1-x1).normalized * std::cos(t) ) - // c1(t) = ( inplane std::sin(t) + v * inplane * std::cos(t) - sm::vec v_x_inplane = v.cross(inplane); - - // Push the central point of the start cap - this is at location vstart - this->vertex_push (vstart, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (colStart, this->vertexColors); - - // Start cap vertices. Draw as a triangle fan, but record indices so that we - // only need a single call to glDrawElements. - for (std::int32_t j = 0; j < segments; j++) { - // t is the angle of the segment - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; - this->vertex_push (vstart+c, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (colStart, this->vertexColors); - } - - // Intermediate, near start cap. Normals point in direction c - for (std::int32_t j = 0; j < segments; j++) { - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; - this->vertex_push (vstart+c, this->vertexPositions); - c.renormalize(); - this->vertex_push (c, this->vertexNormals); - this->vertex_push_colour (colStart, this->vertexColors); - } - - // Intermediate, near end cap. Normals point in direction c - for (std::int32_t j = 0; j < segments; j++) { - float t = (float)j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r_end + v_x_inplane * std::cos(t) * r_end; - this->vertex_push (vend+c, this->vertexPositions); - c.renormalize(); - this->vertex_push (c, this->vertexNormals); - this->vertex_push_colour (colEnd, this->vertexColors); - } - - // Bottom cap vertices - for (std::int32_t j = 0; j < segments; j++) { - float t = (float)j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r_end + v_x_inplane * std::cos(t) * r_end; - this->vertex_push (vend+c, this->vertexPositions); - this->vertex_push (v, this->vertexNormals); - this->vertex_push_colour (colEnd, this->vertexColors); - } - - // Bottom cap. Push centre vertex as the last vertex. - this->vertex_push (vend, this->vertexPositions); - this->vertex_push (v, this->vertexNormals); - this->vertex_push_colour (colEnd, this->vertexColors); - - // Note: number of vertices = segments * 4 + 2. - std::int32_t nverts = (segments * 4) + 2; - - // After creating vertices, push all the indices. - std::uint32_t capMiddle = this->idx; - std::uint32_t capStartIdx = this->idx + 1u; - std::uint32_t endMiddle = this->idx + static_cast(nverts) - 1u; - std::uint32_t endStartIdx = capStartIdx + (3u * segments); - - // Start cap - for (std::int32_t j = 0; j < segments-1; j++) { - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + j); - this->indices.push_back (capStartIdx + 1 + j); - } - // Last one - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + segments - 1); - this->indices.push_back (capStartIdx); - - // Middle sections - for (std::int32_t lsection = 0; lsection < 3; ++lsection) { - capStartIdx = this->idx + 1 + lsection*segments; - endStartIdx = capStartIdx + segments; - // This does sides between start and end. I want to do this three times. - for (std::int32_t j = 0; j < segments; j++) { - // Triangle 1 - this->indices.push_back (capStartIdx + j); - if (j == (segments-1)) { - this->indices.push_back (capStartIdx); - } else { - this->indices.push_back (capStartIdx + 1 + j); - } - this->indices.push_back (endStartIdx + j); - // Triangle 2 - this->indices.push_back (endStartIdx + j); - if (j == (segments-1)) { - this->indices.push_back (endStartIdx); - } else { - this->indices.push_back (endStartIdx + 1 + j); - } - if (j == (segments-1)) { - this->indices.push_back (capStartIdx); - } else { - this->indices.push_back (capStartIdx + j + 1); - } - } - } - - // Bottom cap - for (std::int32_t j = 0; j < segments-1; j++) { - this->indices.push_back (endMiddle); - this->indices.push_back (endStartIdx + j); - this->indices.push_back (endStartIdx + 1 + j); - } - // Last one - this->indices.push_back (endMiddle); - this->indices.push_back (endStartIdx + segments - 1); - this->indices.push_back (endStartIdx); - - // Update idx - this->idx += nverts; - } // end computeFlaredTube with randomly initialized end vertices - - /*! - * Create an open (no end caps) flared tube from \a start to \a end, with radius - * \a r at the start and a colour which transitions from the colour \a colStart - * to \a colEnd. The radius of the end is r_end, given as a function argument. - * - * This has a normal vector for the start and end of the tube, so that the - * circles can be angled. - * - * \param start The start of the tube - * \param end The end of the tube - * \param colStart The tube starting colour - * \param colEnd The tube's ending colour - * \param n_start The normal of the start 'face' - * \param n_end The normal of the end 'face' - * - * \param z_start A vector pointing to the first vertex on the tube. allows - * orientation of tube faces for connected tubes (which is what this primitive - * is all about) - * - * \param r Radius of the tube's start circle - * \param r_end radius of the end circle - * \param segments Number of segments used to render the tube - */ - void computeOpenFlaredTube (sm::vec start, sm::vec end, - sm::vec n_start, sm::vec n_end, - std::array colStart, std::array colEnd, - float r = 1.0f, float r_end = 1.0f, std::int32_t segments = 12) - { - // The vector from start to end defines a vector and a plane. Find a - // 'circle' of points in that plane. - sm::vec vstart = start; - sm::vec vend = end; - sm::vec v = vend - vstart; - v.renormalize(); - - // Two rotations about our face normals - sm::quaternion rotn_start (n_start, sm::mathconst::pi_over_2); - sm::quaternion rotn_end (-n_end, sm::mathconst::pi_over_2); - - sm::vec inplane = v.cross (n_start); - // The above is no good if n_start and v are colinear. In that case choose random inplane: - if (inplane.length() < std::numeric_limits::epsilon()) { - sm::vec rand_vec; - rand_vec.randomize(); - inplane = rand_vec.cross(v); - } - inplane.renormalize(); - - // inplane defines a plane, n_start defines a plane. Our first point is the - // intersection of the two planes and the circle of the end. - sm::vec v_x_inplane = n_start.cross (inplane);// rotn_start * inplane; - v_x_inplane.renormalize(); - - // If r == r_end we want a circular cross section tube (and not an elliptical cross section). - float r_mod = r / v_x_inplane.cross (v).length(); - - // Start ring of vertices. Normals point in direction c - // Now use parameterization of circle inplane = p1-x1 and - // c1(t) = ( (p1-x1).normalized std::sin(t) + v.normalized cross (p1-x1).normalized * std::cos(t) ) - // c1(t) = ( inplane std::sin(t) + v * inplane * std::cos(t) - for (std::int32_t j = 0; j < segments; j++) { - float t = static_cast(j) * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r_mod; - this->vertex_push (vstart + c, this->vertexPositions); - c.renormalize(); - this->vertex_push (c, this->vertexNormals); - this->vertex_push_colour (colStart, this->vertexColors); - } - - // end ring of vertices. Normals point in direction c - v_x_inplane = inplane.cross (n_end); - v_x_inplane.renormalize(); - r_mod = r_end / v_x_inplane.cross (v).length(); - - for (std::int32_t j = 0; j < segments; j++) { - float t = static_cast(j) * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r_end + v_x_inplane * std::cos(t) * r_mod; - this->vertex_push (vend + c, this->vertexPositions); - c.renormalize(); - this->vertex_push (c, this->vertexNormals); - this->vertex_push_colour (colEnd, this->vertexColors); - } - - // Number of vertices - std::int32_t nverts = (segments * 2); - - // After creating vertices, push all the indices. - std::uint32_t sIdx = this->idx; - std::uint32_t eIdx = sIdx + segments; - // This does sides between start and end - for (std::int32_t j = 0; j < segments; j++) { - // Triangle 1 - this->indices.push_back (sIdx + j); - if (j == (segments-1)) { - this->indices.push_back (sIdx); - } else { - this->indices.push_back (sIdx + 1 + j); - } - this->indices.push_back (eIdx + j); - // Triangle 2 - this->indices.push_back (eIdx + j); - if (j == (segments-1)) { - this->indices.push_back (eIdx); - } else { - this->indices.push_back (eIdx + 1 + j); - } - if (j == (segments-1)) { - this->indices.push_back (sIdx); - } else { - this->indices.push_back (sIdx + j + 1); - } - } - - // Update idx - this->idx += nverts; - } // end computeOpenFlaredTube - - // An open, but un-flared tube with no end caps - void computeOpenTube (sm::vec start, sm::vec end, - sm::vec n_start, sm::vec n_end, - std::array colStart, std::array colEnd, - float r = 1.0f, std::int32_t segments = 12) - { - this->computeOpenFlaredTube (start, end, n_start, n_end, colStart, colEnd, r, r, segments); - } - - - void computeFlatQuad (sm::vec c1, sm::vec c2, - sm::vec c3, sm::vec c4, - std::array col) - { - this->computeFlatQuad (c1.less_one_dim(), c2.less_one_dim(), c3.less_one_dim(), c4.less_one_dim(), col); - } - - //! Compute a Quad from 4 arbitrary corners which must be ordered clockwise around the quad. - void computeFlatQuad (sm::vec c1, sm::vec c2, - sm::vec c3, sm::vec c4, - std::array col) - { - // v is the face normal - sm::vec u1 = c1-c2; - sm::vec u2 = c2-c3; - sm::vec v = u2.cross(u1); - v.renormalize(); - - // Push corner vertices - std::size_t vpsz = this->vertexPositions.size(); - this->vertexPositions.resize (vpsz + 12); - for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c1[i]; } - for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c2[i]; } - for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c3[i]; } - for (std::uint32_t i = 0; i < 3u; ++i) { this->vertexPositions[vpsz++] = c4[i]; } - - // Colours/normals - std::size_t vcsz = this->vertexColors.size(); - std::size_t vnsz = this->vertexNormals.size(); - this->vertexColors.resize (vcsz + 12); - this->vertexNormals.resize (vnsz + 12); - for (std::uint32_t i = 0; i < 4u; ++i) { - for (std::uint32_t j = 0; j < 3u; ++j) { - this->vertexColors[vcsz++] = col[j]; - this->vertexNormals[vnsz++] = v[j]; - } - // Alpha 1 as incoming colour does not have alpha - if (this->ncol == 4) { this->vertexColors[vcsz++] = 1.0f; } - } - - std::size_t i0 = this->indices.size(); - this->indices.resize (i0 + 6, 0); - this->indices[i0++] = this->idx; - this->indices[i0++] = this->idx + 2; - this->indices[i0++] = this->idx + 1; - this->indices[i0++] = this->idx; - this->indices[i0++] = this->idx + 3; - this->indices[i0++] = this->idx + 2; - - this->idx += 4; - } - - /*! - * Compute a flat polygon. - * - * Create a flat polygon with segments outer edges. Radius \a r and colour \a col. - * - * \param vstart The centre of the polygon - * \param _ux a vector in the x axis direction for the end face - * \param _uy a vector in the y axis direction. If not same length as _ux, distortions will be seen - * \param col The polygon colour - * \param r Radius - * \param segments Number of segments used to render the polygon - * \param rotation A rotation in the ux/uy plane to orient the vertices of the polygon. - */ - void computeFlatPoly (sm::vec vstart, - sm::vec _ux, sm::vec _uy, - std::array col, - float r = 1.0f, std::int32_t segments = 12, float rotation = 0.0f) - { - // v is a face normal - sm::vec v = _uy.cross(_ux); - v.renormalize(); - - // Push the central point of the start cap - this is at location vstart - this->vertex_push (vstart, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - // Polygon vertices (a triangle fan) - for (std::int32_t j = 0; j < segments; j++) { - // t is the angle of the segment - float t = rotation + j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = _ux * std::sin(t) * r + _uy * std::cos(t) * r; - this->vertex_push (vstart+c, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - } - - // Number of vertices - std::int32_t nverts = segments + 1; - - // After creating vertices, push all the indices. - std::uint32_t capMiddle = this->idx; - std::uint32_t capStartIdx = this->idx + 1; - - // Start cap indices - for (std::int32_t j = 0; j < segments-1; j++) { - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + j); - this->indices.push_back (capStartIdx + 1 + j); - } - // Last one - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + segments - 1); - this->indices.push_back (capStartIdx); - - // Update idx - this->idx += nverts; - } // end computeFlatPoly with ux/uy vectors for faces - - void computeFlatPoly (sm::vec vcentre, - sm::vec _normal, - std::array col, - float r = 1.0f, std::int32_t segments = 12) - { - // Find random _ux given _normal. - _normal.renormalize(); - sm::vec rand_vec; - rand_vec.randomize(); - sm::vec inplane1 = rand_vec.cross (_normal); - inplane1.renormalize(); - sm::vec inplane2 = _normal.cross (inplane1); - this->computeFlatPoly (vcentre, inplane1, inplane2, col, r, segments, 0.0f); - } - - /*! - * Make a ring of radius r, comprised of flat segments - * - * \param ro position of the centre of the ring - * \param rc The ring colour. - * \param r Radius of the ring - * \param t Thickness of the ring - * \param segments Number of tube segments used to render the ring - * \param tfm a transform to apply to the points - */ - void computeRing (sm::vec ro, std::array rc, float r = 1.0f, - float t = 0.1f, std::int32_t segments = 12, - const sm::mat tfm = sm::mat::identity()) - { - float r_in = r - (t * 0.5f); - float r_out = r + (t * 0.5f); - this->computeRingInOut (ro, rc, r_in, r_out, segments, tfm); - } - - /*! - * Make a ring of radius r, comprised of flat segments, specifying inner and outer radii - * - * \param ro position of the centre of the ring - * \param rc The ring colour. - * \param r_in Inner radius of the ring - * \param r_out Outer radius of the ring - * \param segments Number of tube segments used to render the ring - * \param tfm a transform to apply to the points - */ - void computeRingInOut (sm::vec ro, std::array rc, - float r_in = 1.0f, float r_out = 2.0f, std::int32_t segments = 12, - const sm::mat tfm = sm::mat::identity()) - { - for (std::int32_t j = 0; j < segments; j++) { - float segment = sm::mathconst::two_pi * static_cast(j) / segments; - // x and y of inner point - float xin = r_in * std::cos (segment); - float yin = r_in * std::sin (segment); - float xout = r_out * std::cos (segment); - float yout = r_out * std::sin (segment); - std::int32_t segjnext = (j + 1) % segments; - float segnext = sm::mathconst::two_pi * static_cast(segjnext) / segments; - float xin_n = r_in * std::cos (segnext); - float yin_n = r_in * std::sin (segnext); - float xout_n = r_out * std::cos (segnext); - float yout_n = r_out * std::sin (segnext); - - // Now draw a quad - sm::vec c4 = { xin, yin, 0.0f }; - sm::vec c3 = { xout, yout, 0.0f }; - sm::vec c2 = { xout_n, yout_n, 0.0f }; - sm::vec c1 = { xin_n, yin_n, 0.0f }; - this->computeFlatQuad (tfm * (ro + c1), tfm * (ro + c2), tfm * (ro + c3), tfm * (ro + c4), rc); - } - } - - /*! - * Make a ring of radius r, comprised of flat segments - * - * \param ro position of the centre of the ring - * \param rc The ring colour. - * \param mc The mark colour. - * \param m_centre The centre angle of the mark. - * \param r Radius of the ring - * \param t Thickness of the ring - * \param segments Number of tube segments used to render the ring - * \param tfm a transform to apply to the points - */ - void computeMarkedRing (sm::vec ro, std::array rc, - std::array mc, - float m_centre = 0.0f, - float r = 1.0f, - float t = 0.1f, std::int32_t segments = 12, - const sm::mat tfm = sm::mat::identity()) - { - float r_in = r - (t * 0.5f); - float r_out = r + (t * 0.5f); - this->computeMarkedRingInOut (ro, rc, mc, m_centre, r_in, r_out, segments, tfm); - } - - /*! - * Make a ring of radius r, comprised of flat segments, specifying inner and outer radii, - * which has a section coloured in a second colour. - * - * \param ro position of the centre of the ring - * \param rc The ring colour. - * \param mc The mark colour. - * \param m_centre The centre angle of the mark. - * \param m_num_segs The number of segments to colour either size of the centre angle. - * \param r_in Inner radius of the ring - * \param r_out Outer radius of the ring - * \param segments Number of tube segments used to render the ring - * \param tfm a transform to apply to the points - */ - void computeMarkedRingInOut (sm::vec ro, std::array rc, - std::array mc, float m_centre = 0.0f, - float r_in = 1.0f, float r_out = 2.0f, std::int32_t segments = 12, - const sm::mat tfm = sm::mat::identity()) - { - for (std::int32_t j = 0; j < segments; j++) { - float segment = sm::mathconst::two_pi * static_cast(j) / segments; - // x and y of inner point - float xin = r_in * std::cos (segment); - float yin = r_in * std::sin (segment); - float xout = r_out * std::cos (segment); - float yout = r_out * std::sin (segment); - std::int32_t segjnext = (j + 1) % segments; - float segnext = sm::mathconst::two_pi * static_cast(segjnext) / segments; - float xin_n = r_in * std::cos (segnext); - float yin_n = r_in * std::sin (segnext); - float xout_n = r_out * std::cos (segnext); - float yout_n = r_out * std::sin (segnext); - - // Now draw a quad - sm::vec c4 = { xin, yin, 0.0f }; - sm::vec c3 = { xout, yout, 0.0f }; - sm::vec c2 = { xout_n, yout_n, 0.0f }; - sm::vec c1 = { xin_n, yin_n, 0.0f }; - if ((m_centre > segment && m_centre <= segnext) - || (segment == 0.0f && m_centre == 0.0f) - || (segment == 0.0f && m_centre == sm::mathconst::two_pi)) { - this->computeFlatQuad (tfm * (ro + c1), tfm * (ro + c2), tfm * (ro + c3), tfm * (ro + c4), mc); - } else { - this->computeFlatQuad (tfm * (ro + c1), tfm * (ro + c2), tfm * (ro + c3), tfm * (ro + c4), rc); - } - } - } - - /*! - * Sphere, geodesic polygon version. - * - * This function creates an object with exactly one OpenGL vertex per 'geometric - * vertex of the polyhedron'. That means that colouring this object must be - * achieved by colouring the vertices and faces cannot be coloured - * distinctly. Pass in a single colour for the initial object. To recolour, - * modify the content of vertexColors. - * - * \tparam F The type used for the polyhedron computation. Use float or double. - * - * \param so The sphere offset. Where to place this sphere... - * \param sc The sphere colour. - * \param r Radius of the sphere - * \param iterations how many iterations of the geodesic polygon algo to go - * through. Determines faces: - * - * For 0 iterations, get a geodesic with 20 faces *0 - * For 1 iterations, get a geodesic with 80 faces - * For 2 iterations, get a geodesic with 320 faces *1 - * For 3 iterations, get a geodesic with 1280 faces *2 - * For 4 iterations, get a geodesic with 5120 faces *3 - * For 5 iterations, get a geodesic with 20480 faces *4 - * For 6 iterations, get a geodesic with 81920 faces - * For 7 iterations, get a geodesic with 327680 faces - * For 8 iterations, get a geodesic with 1310720 faces - * For 9 iterations, get a geodesic with 5242880 faces - * - * *0: You'll get an icosahedron - * *1: decent graphical results - * *2: excellent graphical results - * *3: You can *just about* see a difference between 4 iterations and 3, but not - * between 4 and 5. - * *4: The iterations limit if F is float (you'll get a runtime error 'vertices - * has wrong size' for iterations>5) - * - * \return The number of vertices in the generated geodesic sphere - */ - template - std::int32_t computeSphereGeo (sm::vec so, std::array sc, float r = 1.0f, std::int32_t iterations = 2) - { - if (iterations < 0) { throw std::runtime_error ("computeSphereGeo: iterations must be positive"); } - // test if type F is float - if constexpr (std::is_same, float>::value == true) { - if (iterations > 5) { - throw std::runtime_error ("computeSphereGeo: For iterations > 5, F needs to be double precision"); - } - } else { - if (iterations > 10) { - throw std::runtime_error ("computeSphereGeo: This is an abitrary iterations limit (10 gives 20971520 faces)"); - } - } - // Note that we need double precision to compute higher iterations of the geodesic (iterations > 5) - sm::geometry::icosahedral_geodesic geo = sm::geometry::make_icosahedral_geodesic (iterations); - - // Now essentially copy geo into vertex buffers - for (auto v : geo.poly.vertices) { - this->vertex_push (v.as_float() * r + so, this->vertexPositions); - this->vertex_push (v.as_float(), this->vertexNormals); - this->vertex_push_colour (sc, this->vertexColors); - } - for (auto f : geo.poly.faces) { - this->indices.push_back (this->idx + f[0]); - this->indices.push_back (this->idx + f[1]); - this->indices.push_back (this->idx + f[2]); - } - // idx is the *vertex index* and should be incremented by the number of vertices in the polyhedron - std::int32_t n_verts = static_cast(geo.poly.vertices.size()); - this->idx += n_verts; - - return n_verts; - } - - /*! - * Sphere, geodesic polygon version with coloured faces - * - * To colour the faces of this polyhedron, update this->vertexColors (for an - * example see mplot::GeodesicVisual). To make faces distinctly colourizable, we - * have to generate 3 OpenGL vertices for each of the geometric vertices in the - * polyhedron. - * - * \tparam F The type used for the polyhedron computation. Use float or double. - * - * \param so The sphere offset. Where to place this sphere... - * \param sc The default colour - * \param r Radius of the sphere - * \param iterations how many iterations of the geodesic polygon algo to go - * through. Determines number of faces - */ - template - std::int32_t computeSphereGeoFaces (sm::vec so, std::array sc, float r = 1.0f, std::int32_t iterations = 2) - { - if (iterations < 0) { throw std::runtime_error ("computeSphereGeo: iterations must be positive"); } - // test if type F is float - if constexpr (std::is_same, float>::value == true) { - if (iterations > 5) { - throw std::runtime_error ("computeSphereGeo: For iterations > 5, F needs to be double precision"); - } - } else { - if (iterations > 10) { - throw std::runtime_error ("computeSphereGeo: This is an abitrary iterations limit (10 gives 20971520 faces)"); - } - } - // Note that we need double precision to compute higher iterations of the geodesic (iterations > 5) - sm::geometry::icosahedral_geodesic geo = sm::geometry::make_icosahedral_geodesic (iterations); - std::int32_t n_faces = static_cast(geo.poly.faces.size()); - - for (std::int32_t i = 0; i < n_faces; ++i) { // For each face in the geodesic... - sm::vec norm = { F{0}, F{0}, F{0} }; - for (auto vtx : geo.poly.faces[i]) { // For each vertex in face... - norm += geo.poly.vertices[vtx]; // Add to the face norm - this->vertex_push (geo.poly.vertices[vtx].as_float() * r + so, this->vertexPositions); - } - sm::vec nf = (norm / F{3}).as_float(); - for (std::int32_t j = 0; j < 3; ++j) { // Faces all have size 3 - this->vertex_push (nf, this->vertexNormals); - this->vertex_push_colour (sc, this->vertexColors); // A default colour - this->indices.push_back (this->idx + (3 * i) + j); // indices is vertex index - } - } - // An index for each vertex of each face. - this->idx += 3 * n_faces; - - return n_faces; - } - - //! Fast computeSphereGeo, which uses constexpr make_icosahedral_geodesic. The - //! resulting vertices and faces are NOT in any kind of order, but ok for - //! plotting, e.g. scatter graph spheres. - template - std::int32_t computeSphereGeoFast (sm::vec so, std::array sc, float r = 1.0f) - { - // test if type F is float - if constexpr (std::is_same, float>::value == true) { - static_assert (iterations <= 5, "computeSphereGeoFast: For iterations > 5, F needs to be double precision"); - } else { - static_assert (iterations <= 10, "computeSphereGeoFast: This is an abitrary iterations limit (10 gives 20971520 faces)"); - } - // Note that we need double precision to compute higher iterations of the geodesic (iterations > 5) - constexpr sm::geometry_ce::icosahedral_geodesic geo = sm::geometry_ce::make_icosahedral_geodesic(); - - // Now essentially copy geo into vertex buffers - for (auto v : geo.poly.vertices) { - this->vertex_push (v.as_float() * r + so, this->vertexPositions); - this->vertex_push (v.as_float(), this->vertexNormals); - this->vertex_push_colour (sc, this->vertexColors); - } - for (auto f : geo.poly.faces) { - this->indices.push_back (this->idx + f[0]); - this->indices.push_back (this->idx + f[1]); - this->indices.push_back (this->idx + f[2]); - } - // idx is the *vertex index* and should be incremented by the number of vertices in the polyhedron - std::int32_t n_verts = static_cast(geo.poly.vertices.size()); - this->idx += n_verts; - - return n_verts; - } - - /*! - * Sphere, 1 colour version. - * - * Code for creating a sphere as part of this model. I'll use a sphere at the centre of the arrows. - * - * \param so The sphere offset. Where to place this sphere... - * \param sc The sphere colour. - * \param r Radius of the sphere - * \param rings Number of rings used to render the sphere - * \param segments Number of segments used to render the sphere - * - * Number of faces should be (2 + rings) * segments - */ - void computeSphere (sm::vec so, std::array sc, - float r = 1.0f, std::int32_t rings = 10, std::int32_t segments = 12) - { - // First cap, draw as a triangle fan, but record indices so that - // we only need a single call to glDrawElements. - float rings0 = -sm::mathconst::pi_over_2; - float _z0 = std::sin(rings0); - float z0 = r * _z0; - float r0 = std::cos(rings0); - float rings1 = sm::mathconst::pi * (-0.5f + 1.0f / rings); - float _z1 = std::sin(rings1); - float z1 = r * _z1; - float r1 = std::cos(rings1); - // Push the central point - this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); - this->vertex_push (0.0f, 0.0f, -1.0f, this->vertexNormals); - this->vertex_push_colour (sc, this->vertexColors); - - std::uint32_t capMiddle = this->idx++; - std::uint32_t ringStartIdx = this->idx; - std::uint32_t lastRingStartIdx = this->idx; - - bool firstseg = true; - for (std::int32_t j = 0; j < segments; j++) { - float segment = sm::mathconst::two_pi * static_cast(j) / segments; - float x = std::cos(segment); - float y = std::sin(segment); - - float _x1 = x*r1; - float x1 = _x1*r; - float _y1 = y*r1; - float y1 = _y1*r; - - this->vertex_push (so[0]+x1, so[1]+y1, so[2]+z1, this->vertexPositions); - this->vertex_push (_x1, _y1, _z1, this->vertexNormals); - this->vertex_push_colour (sc, this->vertexColors); - - if (!firstseg) { - this->indices.push_back (capMiddle); - this->indices.push_back (this->idx-1); - this->indices.push_back (this->idx++); - } else { - this->idx++; - firstseg = false; - } - } - this->indices.push_back (capMiddle); - this->indices.push_back (this->idx-1); - this->indices.push_back (capMiddle+1); - - // Now add the triangles around the rings - for (std::int32_t i = 2; i < rings; i++) { - - rings0 = sm::mathconst::pi * (-0.5f + static_cast(i) / rings); - _z0 = std::sin(rings0); - z0 = r * _z0; - r0 = std::cos(rings0); - - for (std::int32_t j = 0; j < segments; j++) { - - // "current" segment - float segment = sm::mathconst::two_pi * static_cast(j) / segments; - float x = std::cos(segment); - float y = std::sin(segment); - - // One vertex per segment - float _x0 = x*r0; - float x0 = _x0*r; - float _y0 = y*r0; - float y0 = _y0*r; - - // NB: Only add ONE vertex per segment. ALREADY have the first ring! - this->vertex_push (so[0]+x0, so[1]+y0, so[2]+z0, this->vertexPositions); - // The vertex normal of a vertex that makes up a sphere is - // just a normal vector in the direction of the vertex. - this->vertex_push (_x0, _y0, _z0, this->vertexNormals); - this->vertex_push_colour (sc, this->vertexColors); - - if (j == segments - 1) { - // Last vertex is back to the start - this->indices.push_back (ringStartIdx++); - this->indices.push_back (this->idx); - this->indices.push_back (lastRingStartIdx); - this->indices.push_back (lastRingStartIdx); - this->indices.push_back (this->idx++); - this->indices.push_back (lastRingStartIdx+segments); - } else { - this->indices.push_back (ringStartIdx++); - this->indices.push_back (this->idx); - this->indices.push_back (ringStartIdx); - this->indices.push_back (ringStartIdx); - this->indices.push_back (this->idx++); - this->indices.push_back (this->idx); - } - } - lastRingStartIdx += segments; - } - - // bottom cap - rings0 = sm::mathconst::pi_over_2; - _z0 = std::sin(rings0); - z0 = r * _z0; - r0 = std::cos(rings0); - // Push the central point of the bottom cap - this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); - this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); - this->vertex_push_colour (sc, this->vertexColors); - capMiddle = this->idx++; - firstseg = true; - // No more vertices to push, just do the indices for the bottom cap - ringStartIdx = lastRingStartIdx; - for (std::int32_t j = 0; j < segments; j++) { - if (j != segments - 1) { - this->indices.push_back (capMiddle); - this->indices.push_back (ringStartIdx++); - this->indices.push_back (ringStartIdx); - } else { - // Last segment - this->indices.push_back (capMiddle); - this->indices.push_back (ringStartIdx); - this->indices.push_back (lastRingStartIdx); - } - } - } // end of sphere calculation - - /*! - * Sphere, two colour version. - * - * Code for creating a sphere as part of this model. I'll use a sphere at the - * centre of the arrows. - * - * \param so The sphere offset. Where to place this sphere... - * \param sc The sphere colour. - * \param sc2 The sphere's second colour - used for cap and first ring - * \param r Radius of the sphere - * \param rings Number of rings used to render the sphere - * \param segments Number of segments used to render the sphere - */ - void computeSphere (sm::vec so, std::array sc, std::array sc2, - float r = 1.0f, std::int32_t rings = 10, std::int32_t segments = 12) - { - // First cap, draw as a triangle fan, but record indices so that - // we only need a single call to glDrawElements. - float rings0 = -sm::mathconst::pi_over_2; - float _z0 = std::sin(rings0); - float z0 = r * _z0; - float r0 = std::cos(rings0); - float rings1 = sm::mathconst::pi * (-0.5f + 1.0f / rings); - float _z1 = std::sin(rings1); - float z1 = r * _z1; - float r1 = std::cos(rings1); - // Push the central point - this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); - this->vertex_push (0.0f, 0.0f, -1.0f, this->vertexNormals); - this->vertex_push_colour (sc2, this->vertexColors); - - std::uint32_t capMiddle = this->idx++; - std::uint32_t ringStartIdx = this->idx; - std::uint32_t lastRingStartIdx = this->idx; - - bool firstseg = true; - for (std::int32_t j = 0; j < segments; j++) { - float segment = sm::mathconst::two_pi * static_cast(j) / segments; - float x = std::cos(segment); - float y = std::sin(segment); - - float _x1 = x*r1; - float x1 = _x1*r; - float _y1 = y*r1; - float y1 = _y1*r; - - this->vertex_push (so[0]+x1, so[1]+y1, so[2]+z1, this->vertexPositions); - this->vertex_push (_x1, _y1, _z1, this->vertexNormals); - this->vertex_push_colour (sc2, this->vertexColors); - - if (!firstseg) { - this->indices.push_back (capMiddle); - this->indices.push_back (this->idx-1); - this->indices.push_back (this->idx++); - } else { - this->idx++; - firstseg = false; - } - } - this->indices.push_back (capMiddle); - this->indices.push_back (this->idx-1); - this->indices.push_back (capMiddle+1); - - // Now add the triangles around the rings - for (std::int32_t i = 2; i < rings; i++) { - - rings0 = sm::mathconst::pi * (-0.5f + static_cast(i) / rings); - _z0 = std::sin(rings0); - z0 = r * _z0; - r0 = std::cos(rings0); - - for (std::int32_t j = 0; j < segments; j++) { - - // "current" segment - float segment = sm::mathconst::two_pi * static_cast(j) / segments; - float x = std::cos(segment); - float y = std::sin(segment); - - // One vertex per segment - float _x0 = x*r0; - float x0 = _x0*r; - float _y0 = y*r0; - float y0 = _y0*r; - - // NB: Only add ONE vertex per segment. ALREADY have the first ring! - this->vertex_push (so[0]+x0, so[1]+y0, so[2]+z0, this->vertexPositions); - // The vertex normal of a vertex that makes up a sphere is - // just a normal vector in the direction of the vertex. - this->vertex_push (_x0, _y0, _z0, this->vertexNormals); - if (i == 2 || i > (rings-2)) { - this->vertex_push_colour(sc2, this->vertexColors); - } else { - this->vertex_push_colour (sc, this->vertexColors); - } - if (j == segments - 1) { - // Last vertex is back to the start - this->indices.push_back (ringStartIdx++); - this->indices.push_back (this->idx); - this->indices.push_back (lastRingStartIdx); - this->indices.push_back (lastRingStartIdx); - this->indices.push_back (this->idx++); - this->indices.push_back (lastRingStartIdx+segments); - } else { - this->indices.push_back (ringStartIdx++); - this->indices.push_back (this->idx); - this->indices.push_back (ringStartIdx); - this->indices.push_back (ringStartIdx); - this->indices.push_back (this->idx++); - this->indices.push_back (this->idx); - } - } - lastRingStartIdx += segments; - } - - // bottom cap - rings0 = sm::mathconst::pi_over_2; - _z0 = std::sin(rings0); - z0 = r * _z0; - r0 = std::cos(rings0); - // Push the central point of the bottom cap - this->vertex_push (so[0]+0.0f, so[1]+0.0f, so[2]+z0, this->vertexPositions); - this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); - this->vertex_push_colour (sc2, this->vertexColors); - capMiddle = this->idx++; - firstseg = true; - // No more vertices to push, just do the indices for the bottom cap - ringStartIdx = lastRingStartIdx; - for (std::int32_t j = 0; j < segments; j++) { - if (j != segments - 1) { - this->indices.push_back (capMiddle); - this->indices.push_back (ringStartIdx++); - this->indices.push_back (ringStartIdx); - } else { - // Last segment - this->indices.push_back (capMiddle); - this->indices.push_back (ringStartIdx); - this->indices.push_back (lastRingStartIdx); - } - } - } - - /*! - * Compute an ellipsoid surface of the form x*x/a*a + y*y/b*b + z*z/c*c = 1 - * - * so is the offset position for the ellipsoid - * - * sc is the colour at one end of the z axis - * - * sc2 is the colour at the other end - * - * abc are the three ellipsoid parameters - * - * rings is the number of rings along the z axis - * - * segments is the number of segments in each ring along the z axis - * - * tr transform matrix to apply to each point in the ellipse (applied before so is applied - * as a transform) - */ - void computeEllipsoid (sm::vec so, - std::array sc, - std::array sc2, - sm::vec abc, - std::int32_t rings = 10, std::int32_t segments = 12, - sm::mat tr = sm::mat::identity()) - { - // We have two angular parameters t and t2. t in range 0-2pi and t2 in range 0-pi. t - // gives the 'xy' ellipse; t2 gives the change in size of the xy ellipse as the z axis - // is traversed. - float t = 0.0f; - float t2 = 0.0f; - // used computing normals - sm::vec two_over_abcsq = 2.0f / abc.sq(); - // Holding the coordinates of each point on the ellipsoid as we compute it - sm::vec p = {}; - // The normal vector - sm::vec n = {}; - - // sm::vec versions of the colours - sm::vec _sc = {}; - _sc.set_from (sc); - sm::vec _sc2 = {}; - _sc2.set_from (sc2); - - // Push the central point - p = { 0, 0, abc[2] }; - this->vertex_push (so + (tr * p).less_one_dim(), this->vertexPositions); - n = { 0, 0, 1 }; - this->vertex_push (n, this->vertexNormals); - this->vertex_push_colour (_sc, this->vertexColors); - - std::uint32_t capMiddle = this->idx++; - std::uint32_t ringStartIdx = this->idx; - std::uint32_t lastRingStartIdx = this->idx; - - t2 = sm::mathconst::pi / rings; - p[2] = abc[2] * std::cos(t2); - - bool firstseg = true; - for (std::int32_t j = 0; j < segments; j++) { - - t = sm::mathconst::two_pi * static_cast(j) / segments; - p[0] = abc[0] * std::cos(t) * std::sin(t2); - p[1] = abc[1] * std::sin(t) * std::sin(t2); - - sm::vec<> pp = (tr * p).less_one_dim(); - this->vertex_push (so + pp, this->vertexPositions); - - n = (tr * (p * two_over_abcsq)).less_one_dim(); - n.renormalize(); - this->vertex_push (n, this->vertexNormals); - - sm::vec sc_ring = _sc * (1.0f - 1.0f / rings) + _sc2 * 1.0f / rings; - this->vertex_push_colour (sc_ring, this->vertexColors); - - if (!firstseg) { - this->indices.push_back (capMiddle); - this->indices.push_back (this->idx-1); - this->indices.push_back (this->idx++); - } else { - this->idx++; - firstseg = false; - } - } - this->indices.push_back (capMiddle); - this->indices.push_back (this->idx-1); - this->indices.push_back (capMiddle+1); - - // Now add the triangles around the rings - for (std::int32_t i = 2; i < rings; i++) { - - t2 = sm::mathconst::pi * (static_cast(i) / rings); - p[2] = abc[2] * std::cos(t2); - - sm::vec sc_ring = _sc * (1.0f - static_cast(i) / rings) + _sc2 * static_cast(i) / rings; - - for (std::int32_t j = 0; j < segments; j++) { - - // "current" segment - t = sm::mathconst::two_pi * static_cast(j) / segments; - p[0] = abc[0] * std::cos(t) * std::sin(t2); - p[1] = abc[1] * std::sin(t) * std::sin(t2); - - // NB: Only add ONE vertex per segment. ALREADY have the first ring! - sm::vec<> pp = (tr * p).less_one_dim(); - this->vertex_push (so + pp, this->vertexPositions); - // The vertex normal of a vertex that makes up a sphere is - // just a normal vector in the direction of the vertex. - n = (tr * (p * two_over_abcsq)).less_one_dim(); - n.renormalize(); - this->vertex_push (n, this->vertexNormals); - - this->vertex_push_colour (sc_ring, this->vertexColors); - - if (j == segments - 1) { - // Last vertex is back to the start - this->indices.push_back (ringStartIdx++); - this->indices.push_back (this->idx); - this->indices.push_back (lastRingStartIdx); - this->indices.push_back (lastRingStartIdx); - this->indices.push_back (this->idx++); - this->indices.push_back (lastRingStartIdx+segments); - } else { - this->indices.push_back (ringStartIdx++); - this->indices.push_back (this->idx); - this->indices.push_back (ringStartIdx); - this->indices.push_back (ringStartIdx); - this->indices.push_back (this->idx++); - this->indices.push_back (this->idx); - } - } - lastRingStartIdx += segments; - } - - // bottom cap - - // Push the central point of the bottom cap - p = { 0, 0, -abc[2] }; - this->vertex_push (so + (tr * p).less_one_dim(), this->vertexPositions); - n = { 0, 0, -1 }; - this->vertex_push (n, this->vertexNormals); - this->vertex_push_colour (_sc2, this->vertexColors); - capMiddle = this->idx++; - firstseg = true; - // No more vertices to push, just do the indices for the bottom cap - ringStartIdx = lastRingStartIdx; - for (std::int32_t j = 0; j < segments; j++) { - if (j != segments - 1) { - this->indices.push_back (capMiddle); - this->indices.push_back (ringStartIdx++); - this->indices.push_back (ringStartIdx); - } else { - // Last segment - this->indices.push_back (capMiddle); - this->indices.push_back (ringStartIdx); - this->indices.push_back (lastRingStartIdx); - } - } - } - - /*! - * Compute vertices for an icosahedron. - */ - void computeIcosahedron (sm::vec centre, - std::array, 20> face_colours, - float r = 1.0f) // radius or side length? - { - sm::geometry::polyhedron ico = sm::geometry::icosahedron(); - - for (std::int32_t j = 0; j < 20; ++j) { - // Compute the face normal - sm::vec norml = (ico.vertices[ico.faces[j][0]] + ico.vertices[ico.faces[j][1]] + ico.vertices[ico.faces[j][2]])/3.0f; - this->vertex_push (centre + (ico.vertices[ico.faces[j][0]] * r), this->vertexPositions); - this->vertex_push (centre + (ico.vertices[ico.faces[j][1]] * r), this->vertexPositions); - this->vertex_push (centre + (ico.vertices[ico.faces[j][2]] * r), this->vertexPositions); - for (std::int32_t i = 0; i < 3; ++i) { - this->vertex_push (norml, this->vertexNormals); - this->vertex_push_colour (face_colours[j], this->vertexColors); - } - // Indices... - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+1); - this->indices.push_back (this->idx+2); - this->idx += 3; - } - } - - /*! - * Create a cone. - * - * \param centre The centre of the cone - would be the end of the line - * - * \param tip The tip of the cone - * - * \param ringoffset Move the ring forwards or backwards along the vector from - * \a centre to \a tip. This is positive or negative proportion of tip - centre. - * - * \param col The cone colour - * - * \param r Radius of the ring - * - * \param segments Number of segments used to render the tube - */ - void computeCone (sm::vec centre, - sm::vec tip, - float ringoffset, - std::array col, - float r = 1.0f, std::int32_t segments = 12) - { - // Cone is drawn as a base ring around a centre-of-the-base vertex, an - // intermediate ring which is on the base ring, but has different normals, a - // 'ring' around the tip (with suitable normals) and a 'tip' vertex - - sm::vec vbase = centre; - sm::vec vtip = tip; - sm::vec v = vtip - vbase; - v.renormalize(); - - // circle in a plane defined by a point and a normal - sm::vec rand_vec; - rand_vec.randomize(); - sm::vec inplane = rand_vec.cross(v); - inplane.renormalize(); - sm::vec v_x_inplane = v.cross(inplane); - - // Push the central point of the start cap - this is at location vstart - this->vertex_push (vbase, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - // Base ring with normals in direction -v - for (std::int32_t j = 0; j < segments; j++) { - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; - // Subtract the vector which makes this circle - c = c + (v * ringoffset); - this->vertex_push (vbase+c, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - } - - // Intermediate ring of vertices around/aligned with the base ring with normals in direction c - for (std::int32_t j = 0; j < segments; j++) { - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; - c = c + (v * ringoffset); - this->vertex_push (vbase+c, this->vertexPositions); - c.renormalize(); - this->vertex_push (c, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - } - - // Intermediate ring of vertices around the tip with normals direction c - for (std::int32_t j = 0; j < segments; j++) { - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = inplane * std::sin(t) * r + v_x_inplane * std::cos(t) * r; - c = c + (v * ringoffset); - this->vertex_push (vtip, this->vertexPositions); - c.renormalize(); - this->vertex_push (c, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - } - - // Push tip vertex as the last vertex, normal is in direction v - this->vertex_push (vtip, this->vertexPositions); - this->vertex_push (v, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - // Number of vertices = segments * 3 + 2. - std::int32_t nverts = segments * 3 + 2; - - // After creating vertices, push all the indices. - std::uint32_t capMiddle = this->idx; - std::uint32_t capStartIdx = this->idx + 1; - std::uint32_t endMiddle = this->idx + static_cast(nverts) - 1u; - std::uint32_t endStartIdx = capStartIdx; - - // Base of the cone - for (std::int32_t j = 0; j < segments-1; j++) { - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + j); - this->indices.push_back (capStartIdx + 1 + j); - } - // Last tri of base - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + segments - 1); - this->indices.push_back (capStartIdx); - - // Middle sections - for (std::int32_t lsection = 0; lsection < 2; ++lsection) { - capStartIdx = this->idx + 1 + lsection*segments; - endStartIdx = capStartIdx + segments; - for (std::int32_t j = 0; j < segments; j++) { - // Triangle 1: - this->indices.push_back (capStartIdx + j); - if (j == (segments-1)) { - this->indices.push_back (capStartIdx); - } else { - this->indices.push_back (capStartIdx + 1 + j); - } - this->indices.push_back (endStartIdx + j); - // Triangle 2: - this->indices.push_back (endStartIdx + j); - if (j == (segments-1)) { - this->indices.push_back (endStartIdx); - } else { - this->indices.push_back (endStartIdx + 1 + j); - } - if (j == (segments-1)) { - this->indices.push_back (capStartIdx); - } else { - this->indices.push_back (capStartIdx + j + 1); - } - } - } - - // tip - for (std::int32_t j = 0; j < segments-1; j++) { - this->indices.push_back (endMiddle); - this->indices.push_back (endStartIdx + j); - this->indices.push_back (endStartIdx + 1 + j); - } - // Last triangle of tip - this->indices.push_back (endMiddle); - this->indices.push_back (endStartIdx + segments - 1); - this->indices.push_back (endStartIdx); - - // Update idx - this->idx += nverts; - } // end of cone calculation - - //! Compute a line with a single colour - void computeLine (sm::vec start, sm::vec end, - sm::vec _uz, - std::array col, - float w = 0.1f, float thickness = 0.01f, float shorten = 0.0f) - { - this->computeLine (start, end, _uz, col, col, w, thickness, shorten); - } - - /*! - * Create a line from \a start to \a end, with width \a w and a colour which - * transitions from the colour \a colStart to \a colEnd. The thickness of the - * line in the z direction is \a thickness - * - * \param start The start of the tube - * \param end The end of the tube - * \param _uz Dirn of z (up) axis for end face of line. Should be normalized. - * \param colStart The tube staring colour - * \param colEnd The tube's ending colour - * \param w width of line - * \param thickness The thickness/depth of the line in uy direction - * \param shorten An amount by which to shorten the length of the line at each end. - */ - void computeLine (sm::vec start, sm::vec end, - sm::vec _uz, - std::array colStart, std::array colEnd, - float w = 0.1f, float thickness = 0.01f, float shorten = 0.0f) - { - // There are always 8 segments for this line object, 2 at each of 4 corners - const std::int32_t segments = 8; - - // The vector from start to end defines direction of the tube - sm::vec vstart = start; - sm::vec vend = end; - sm::vec v = vend - vstart; - v.renormalize(); - - // If shorten is not 0, then modify vstart and vend - if (shorten > 0.0f) { - vstart = start + v * shorten; - vend = end - v * shorten; - } - - // vv is normal to v and _uz - sm::vec vv = v.cross(_uz); - vv.renormalize(); - - // Push the central point of the start cap - this is at location vstart - this->vertex_push (vstart, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (colStart, this->vertexColors); - - // Compute the 'face angles' that will give the correct width and thickness for the line - std::array angles; - float w_ = w * 0.5f; - float d_ = thickness * 0.5f; - float r = std::sqrt (w_ * w_ + d_ * d_); - angles[0] = std::acos (w_ / r); - angles[1] = angles[0]; - angles[2] = sm::mathconst::pi - angles[0]; - angles[3] = angles[2]; - angles[4] = sm::mathconst::pi + angles[0]; - angles[5] = angles[4]; - angles[6] = sm::mathconst::two_pi - angles[0]; - angles[7] = angles[6]; - // The normals for the vertices around the line - std::array, 8> norms = { vv, _uz, _uz, -vv, -vv, -_uz, -_uz, vv }; - - // Start cap vertices (a triangle fan) - for (std::int32_t j = 0; j < segments; j++) { - sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; - this->vertex_push (vstart+c, this->vertexPositions); - this->vertex_push (-v, this->vertexNormals); - this->vertex_push_colour (colStart, this->vertexColors); - } - - // Intermediate, near start cap. Normals point outwards. Need Additional vertices - for (std::int32_t j = 0; j < segments; j++) { - sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; - this->vertex_push (vstart+c, this->vertexPositions); - this->vertex_push (norms[j], this->vertexNormals); - this->vertex_push_colour (colStart, this->vertexColors); - } - - // Intermediate, near end cap. Normals point in direction c - for (std::int32_t j = 0; j < segments; j++) { - sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; - this->vertex_push (vend+c, this->vertexPositions); - this->vertex_push (norms[j], this->vertexNormals); - this->vertex_push_colour (colEnd, this->vertexColors); - } - - // Bottom cap vertices - for (std::int32_t j = 0; j < segments; j++) { - sm::vec c = _uz * std::sin(angles[j]) * r + vv * std::cos(angles[j]) * r; - this->vertex_push (vend+c, this->vertexPositions); - this->vertex_push (v, this->vertexNormals); - this->vertex_push_colour (colEnd, this->vertexColors); - } - - // Bottom cap. Push centre vertex as the last vertex. - this->vertex_push (vend, this->vertexPositions); - this->vertex_push (v, this->vertexNormals); - this->vertex_push_colour (colEnd, this->vertexColors); - - // Number of vertices = segments * 4 + 2. - std::int32_t nverts = (segments * 4) + 2; - - // After creating vertices, push all the indices. - std::uint32_t capMiddle = this->idx; - std::uint32_t capStartIdx = this->idx + 1u; - std::uint32_t endMiddle = this->idx + static_cast(nverts) - 1u; - std::uint32_t endStartIdx = capStartIdx + (3u * segments); - - // Start cap indices - for (std::int32_t j = 0; j < segments-1; j++) { - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + j); - this->indices.push_back (capStartIdx + 1 + j); - } - // Last one - this->indices.push_back (capMiddle); - this->indices.push_back (capStartIdx + segments - 1); - this->indices.push_back (capStartIdx); - - // Middle sections - for (std::int32_t lsection = 0; lsection < 3; ++lsection) { - capStartIdx = this->idx + 1 + lsection*segments; - endStartIdx = capStartIdx + segments; - for (std::int32_t j = 0; j < segments; j++) { - this->indices.push_back (capStartIdx + j); - if (j == (segments-1)) { - this->indices.push_back (capStartIdx); - } else { - this->indices.push_back (capStartIdx + 1 + j); - } - this->indices.push_back (endStartIdx + j); - this->indices.push_back (endStartIdx + j); - if (j == (segments-1)) { - this->indices.push_back (endStartIdx); - } else { - this->indices.push_back (endStartIdx + 1 + j); - } - if (j == (segments-1)) { - this->indices.push_back (capStartIdx); - } else { - this->indices.push_back (capStartIdx + j + 1); - } - } - } - - // bottom cap - for (std::int32_t j = 0; j < segments-1; j++) { - this->indices.push_back (endMiddle); - this->indices.push_back (endStartIdx + j); - this->indices.push_back (endStartIdx + 1 + j); - } - this->indices.push_back (endMiddle); - this->indices.push_back (endStartIdx + segments - 1); - this->indices.push_back (endStartIdx); - - // Update idx - this->idx += nverts; - } // end computeLine - - // Like computeLine, but this line has no thickness. - void computeFlatLine (sm::vec start, sm::vec end, - sm::vec _uz, - std::array col, - float w = 0.1f, float shorten = 0.0f) - { - // The vector from start to end defines direction of the tube - sm::vec vstart = start; - sm::vec vend = end; - sm::vec v = vend - vstart; - v.renormalize(); - - // If shorten is not 0, then modify vstart and vend - if (shorten > 0.0f) { - vstart = start + v * shorten; - vend = end - v * shorten; - } - - // vv is normal to v and _uz - sm::vec vv = v.cross(_uz); - vv.renormalize(); - - // corners of the line, and the start angle is determined from vv and w - sm::vec ww = vv * w * 0.5f; - sm::vec c1 = vstart + ww; - sm::vec c2 = vstart - ww; - sm::vec c3 = vend - ww; - sm::vec c4 = vend + ww; - - this->vertex_push (c1, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c2, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c3, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c4, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - // Number of vertices = segments * 4 + 2. - std::int32_t nverts = 4; - - // After creating vertices, push all the indices. - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+1); - this->indices.push_back (this->idx+2); - - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+2); - this->indices.push_back (this->idx+3); - - // Update idx - this->idx += nverts; - - } // end computeFlatLine - - // Like computeFlatLine but with option to add rounded start/end caps (I lazily - // draw a whole circle around start/end to achieve this, rather than figuring - // out a semi-circle). - void computeFlatLineRnd (sm::vec start, sm::vec end, - sm::vec _uz, - std::array col, - float w = 0.1f, float shorten = 0.0f, bool startcaps = true, bool endcaps = true) - { - // The vector from start to end defines direction of the tube - sm::vec vstart = start; - sm::vec vend = end; - sm::vec v = vend - vstart; - v.renormalize(); - - // If shorten is not 0, then modify vstart and vend - if (shorten > 0.0f) { - vstart = start + v * shorten; - vend = end - v * shorten; - } - - // vv is normal to v and _uz - sm::vec vv = v.cross(_uz); - vv.renormalize(); - - // corners of the line, and the start angle is determined from vv and w - sm::vec ww = vv * w * 0.5f; - sm::vec c1 = vstart + ww; - sm::vec c2 = vstart - ww; - sm::vec c3 = vend - ww; - sm::vec c4 = vend + ww; - - std::int32_t segments = 12; - float r = 0.5f * w; - std::uint32_t startvertices = 0u; - if (startcaps) { - // Push the central point of the start cap - this is at location vstart - this->vertex_push (vstart, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - ++startvertices; - // Start cap vertices (a triangle fan) - for (std::int32_t j = 0; j < segments; j++) { - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = { std::sin(t) * r, std::cos(t) * r, 0.0f }; - this->vertex_push (vstart+c, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - ++startvertices; - } - } - - this->vertex_push (c1, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c2, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c3, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c4, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - std::uint32_t endvertices = 0u; - if (endcaps) { - // Push the central point of the end cap - this is at location vend - this->vertex_push (vend, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - ++endvertices; - // End cap vertices (a triangle fan) - for (std::int32_t j = 0; j < segments; j++) { - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c = { std::sin(t) * r, std::cos(t) * r, 0.0f }; - this->vertex_push (vend+c, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - ++endvertices; - } - } - - // After creating vertices, push all the indices. - - if (startcaps) { // prolly startcaps, for flexibility - std::uint32_t topcap = this->idx; - for (std::int32_t j = 0; j < segments; j++) { - std::int32_t inc1 = 1+j; - std::int32_t inc2 = 1+((j+1)%segments); - this->indices.push_back (topcap); - this->indices.push_back (topcap+inc1); - this->indices.push_back (topcap+inc2); - } - this->idx += startvertices; - } - - // The line itself - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+1); - this->indices.push_back (this->idx+2); - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+2); - this->indices.push_back (this->idx+3); - // Update idx - this->idx += 4; - - if (endcaps) { - std::uint32_t botcap = this->idx; - for (std::int32_t j = 0; j < segments; j++) { - std::int32_t inc1 = 1+j; - std::int32_t inc2 = 1+((j+1)%segments); - this->indices.push_back (botcap); - this->indices.push_back (botcap+inc1); - this->indices.push_back (botcap+inc2); - } - this->idx += endvertices; - } - } // end computeFlatLine - - /*! - * Like computeFlatLine, but this line has no thickness and you can provide the - * previous and next data points so that this line, the previous line and the - * next line can line up perfectly without drawing a circular rounded 'end cap'! - * - * This code assumes that the coordinates prev, start, end, next all lie on a 2D - * plane normal to _uz. In fact, the 3D coordinates start, end, prev and next - * will all be projected onto the plane defined by _uz, so that they can be - * reduced to 2D coordinates. This then allows crossing points of lines to be - * computed. - * - * If you want to make a ribbon between points that do *not* lie on a 2D plane, - * you'll need to write another graphics primitive function. - */ - void computeFlatLine (sm::vec start, sm::vec end, - sm::vec prev, sm::vec next, - sm::vec _uz, - std::array col, - float w = 0.1f) - { - // Corner coordinates for this line section - sm::vec c1 = { 0.0f }; - sm::vec c2 = { 0.0f }; - sm::vec c3 = { 0.0f }; - sm::vec c4 = { 0.0f }; - - // Ensure _uz is a unit vector - sm::vec __uz = _uz; - __uz.renormalize(); - - // First find the rotation to make __uz into the actual unit z dirn - sm::quaternion rotn; - sm::vec basis_rotn_axis = __uz.cross (sm::vec<>::uz()); - if (basis_rotn_axis.length() > 0.0f) { - float basis_rotn_angle = __uz.angle (sm::vec<>::uz(), basis_rotn_axis); - rotn.rotate (basis_rotn_axis, basis_rotn_angle); - } // else nothing to do - basis rotn is null - - // Transform so that start is the origin - // sm::vec s_o = { 0.0f }; // by defn - sm::vec e_o = end - start; - sm::vec p_o = prev - start; - sm::vec n_o = next - start; - - // Apply basis rotation just to the end point. e_b: 'end point in rotated basis' - sm::vec e_b = rotn * e_o; - - // Use the vector from start to end as the in-plane x dirn. Do this AFTER - // first coord rotn. In other words: find the rotation about the new unit z - // direction to force the end point to be on the x axis - sm::vec plane_x = e_b; // - s_b but s_b is (0,0,0) by defn - plane_x.renormalize(); - sm::vec plane_y = sm::vec<>::uz().cross (plane_x); - plane_y.renormalize(); - // Find the in-plane coordinates in the rotated plane system - sm::vec e_p = { plane_x.dot (e_b), plane_y.dot (e_b), sm::vec<>::uz().dot (e_b) }; - - // One epsilon is exacting - if (std::abs(e_p[2]) > std::numeric_limits::epsilon()) { - throw std::runtime_error ("uz not orthogonal to the line start -> end?"); - } - - // From e_p and e_b (which should both be in a 2D plane) figure out what - // angle of rotation brings e_b into the x axis - float inplane_rotn_angle = e_b.angle (e_p, sm::vec<>::uz()); - sm::quaternion inplane_rotn (sm::vec<>::uz(), inplane_rotn_angle); - - // Apply the in-plane rotation to the basis rotation - rotn.premultiply (inplane_rotn); - - // Transform points - sm::vec p_p = rotn * p_o; - sm::vec n_p = rotn * n_o; - //vec s_p = rotn * s_o; // not necessary, s_p = (0,0,0) by defn - - // Line crossings time. - sm::vec c1_p = { 0.0f }; // 2D crossing coords that we're going to find - sm::vec c2_p = { 0.0f }; - sm::vec c3_p = e_p.less_one_dim(); - sm::vec c4_p = e_p.less_one_dim(); - - // 3 lines on each side. l_p, l_c (current) and l_n. Each has two ends. l_p_1, l_p_2 etc. - - // 'prev' 'cur' and 'next' vectors - sm::vec p_vec = (/*s_p*/ -p_p).less_one_dim(); - sm::vec c_vec = e_p.less_one_dim(); - sm::vec n_vec = (n_p - e_p).less_one_dim(); - - sm::vec p_ortho = (/*s_p*/ - p_p).cross (sm::vec<>::uz()).less_one_dim(); - p_ortho.renormalize(); - sm::vec c_ortho = (e_p /*- s_p*/).cross (sm::vec<>::uz()).less_one_dim(); - c_ortho.renormalize(); - sm::vec n_ortho = (n_p - e_p).cross (sm::vec<>::uz()).less_one_dim(); - n_ortho.renormalize(); - - const float hw = w / 2.0f; - - sm::vec l_p_1 = p_p.less_one_dim() + (p_ortho * hw) - p_vec; // makes it 3 times as long as the line. - sm::vec l_p_2 = /*s_p.less_one_dim() +*/ (p_ortho * hw) + p_vec; - sm::vec l_c_1 = /*s_p.less_one_dim() +*/ (c_ortho * hw) - c_vec; - sm::vec l_c_2 = e_p.less_one_dim() + (c_ortho * hw) + c_vec; - sm::vec l_n_1 = e_p.less_one_dim() + (n_ortho * hw) - n_vec; - sm::vec l_n_2 = n_p.less_one_dim() + (n_ortho * hw) + n_vec; - - std::bitset<2> isect = sm::geometry::segments_intersect (l_p_1, l_p_2, l_c_1, l_c_2); - if (isect.test(0) == true && isect.test(1) == false) { // test for intersection but not colinear - c1_p = sm::geometry::crossing_point (l_p_1, l_p_2, l_c_1, l_c_2); - } else if (isect.test(0) == true && isect.test(1) == true) { - c1_p = /*s_p.less_one_dim() +*/ (c_ortho * hw); - } else { // no intersection. prev could have been start - c1_p = /*s_p.less_one_dim() +*/ (c_ortho * hw); - } - isect = sm::geometry::segments_intersect (l_c_1, l_c_2, l_n_1, l_n_2); - if (isect.test(0) == true && isect.test(1) == false) { - c4_p = sm::geometry::crossing_point (l_c_1, l_c_2, l_n_1, l_n_2); - } else if (isect.test(0) == true && isect.test(1) == true) { - c4_p = e_p.less_one_dim() + (c_ortho * hw); - } else { // no intersection, prev could have been end - c4_p = e_p.less_one_dim() + (c_ortho * hw); - } - - // o for 'other side'. Could re-use vars in future version. Or just subtract (*_ortho * w) from each. - sm::vec o_l_p_1 = p_p.less_one_dim() - (p_ortho * hw) - p_vec; // makes it 3 times as long as the line. - sm::vec o_l_p_2 = /*s_p.less_one_dim()*/ - (p_ortho * hw) + p_vec; - sm::vec o_l_c_1 = /*s_p.less_one_dim()*/ - (c_ortho * hw) - c_vec; - sm::vec o_l_c_2 = e_p.less_one_dim() - (c_ortho * hw) + c_vec; - sm::vec o_l_n_1 = e_p.less_one_dim() - (n_ortho * hw) - n_vec; - sm::vec o_l_n_2 = n_p.less_one_dim() - (n_ortho * hw) + n_vec; - - isect = sm::geometry::segments_intersect (o_l_p_1, o_l_p_2, o_l_c_1, o_l_c_2); - if (isect.test(0) == true && isect.test(1) == false) { // test for intersection but not colinear - c2_p = sm::geometry::crossing_point (o_l_p_1, o_l_p_2, o_l_c_1, o_l_c_2); - } else if (isect.test(0) == true && isect.test(1) == true) { - c2_p = /*s_p.less_one_dim()*/ - (c_ortho * hw); - } else { // no intersection. prev could have been start - c2_p = /*s_p.less_one_dim()*/ - (c_ortho * hw); - } - - isect = sm::geometry::segments_intersect (o_l_c_1, o_l_c_2, o_l_n_1, o_l_n_2); - if (isect.test(0) == true && isect.test(1) == false) { - c3_p = sm::geometry::crossing_point (o_l_c_1, o_l_c_2, o_l_n_1, o_l_n_2); - } else if (isect.test(0) == true && isect.test(1) == true) { - c3_p = e_p.less_one_dim() - (c_ortho * hw); - } else { // no intersection. next could have been end - c3_p = e_p.less_one_dim() - (c_ortho * hw); - } - - // Transform and rotate back into c1-c4 - sm::quaternion rotn_inv = rotn.invert(); - c1 = rotn_inv * c1_p.plus_one_dim() + start; - c2 = rotn_inv * c2_p.plus_one_dim() + start; - c3 = rotn_inv * c3_p.plus_one_dim() + start; - c4 = rotn_inv * c4_p.plus_one_dim() + start; - - // Now create the vertices from these four corners, c1-c4 - this->vertex_push (c1, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c2, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c3, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c4, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+1); - this->indices.push_back (this->idx+2); - - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+2); - this->indices.push_back (this->idx+3); - - // Update idx - this->idx += 4; - } // end computeFlatLine that joins perfectly - - //! Make a joined up line with previous. - void computeFlatLineP (sm::vec start, sm::vec end, - sm::vec prev, - sm::vec _uz, - std::array col, - float w = 0.1f) - { - this->computeFlatLine (start, end, prev, end, _uz, col, w); - } // end computeFlatLine that joins perfectly with prev - - //! Flat line, joining up with next - void computeFlatLineN (sm::vec start, sm::vec end, - sm::vec next, - sm::vec _uz, - std::array col, - float w = 0.1f) - { - this->computeFlatLine (start, end, start, next, _uz, col, w); - } - - // Like computeLine, but this line has no thickness and it's dashed. - // dashlen: the length of dashes - // gap prop: The proportion of dash length used for the gap - void computeFlatDashedLine (sm::vec start, sm::vec end, - sm::vec _uz, - std::array col, - float w = 0.1f, float shorten = 0.0f, - float dashlen = 0.1f, float gapprop = 0.3f) - { - if (dashlen == 0.0f) { return; } - - // The vector from start to end defines direction of the line - sm::vec vstart = start; - sm::vec vend = end; - - sm::vec v = vend - vstart; - float linelen = v.length(); - v.renormalize(); - - // If shorten is not 0, then modify vstart and vend - if (shorten > 0.0f) { - vstart = start + v * shorten; - vend = end - v * shorten; - linelen = v.length() - shorten * 2.0f; - } - - // vv is normal to v and _uz - sm::vec vv = v.cross(_uz); - vv.renormalize(); - - // Loop, creating the dashes - sm::vec dash_s = vstart; - sm::vec dash_e = dash_s + v * dashlen; - sm::vec dashes = dash_e - vstart; - - while (dashes.length() < linelen) { - - // corners of the line, and the start angle is determined from vv and w - sm::vec ww = vv * w * 0.5f; - sm::vec c1 = dash_s + ww; - sm::vec c2 = dash_s - ww; - sm::vec c3 = dash_e - ww; - sm::vec c4 = dash_e + ww; - - this->vertex_push (c1, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c2, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c3, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - this->vertex_push (c4, this->vertexPositions); - this->vertex_push (_uz, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - - // Number of vertices = segments * 4 + 2. - std::int32_t nverts = 4; - - // After creating vertices, push all the indices. - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+1); - this->indices.push_back (this->idx+2); - - this->indices.push_back (this->idx); - this->indices.push_back (this->idx+2); - this->indices.push_back (this->idx+3); - - // Update idx - this->idx += nverts; - - // Next dash - dash_s = dash_e + v * dashlen * gapprop; - dash_e = dash_s + v * dashlen; - dashes = dash_e - vstart; - } - - } // end computeFlatDashedLine - - // Compute a flat line circle outline - void computeFlatCircleLine (sm::vec centre, sm::vec norm, sm::vec inplane, float radius, - float linewidth, std::array col, std::int32_t segments = 128) - { - inplane.renormalize(); - sm::vec norm_x_inplane = norm.cross(inplane); - - float half_lw = linewidth / 2.0f; - float r_in = radius - half_lw; - float r_out = radius + half_lw; - // Inner ring at radius radius-linewidth/2 with normals in direction norm; - // Outer ring at radius radius+linewidth/2 with normals also in direction norm - for (std::int32_t j = 0; j < segments; j++) { - float t = j * sm::mathconst::two_pi / static_cast(segments); - sm::vec c_in = inplane * std::sin(t) * r_in + norm_x_inplane * std::cos(t) * r_in; - this->vertex_push (centre+c_in, this->vertexPositions); - this->vertex_push (norm, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - sm::vec c_out = inplane * std::sin(t) * r_out + norm_x_inplane * std::cos(t) * r_out; - this->vertex_push (centre+c_out, this->vertexPositions); - this->vertex_push (norm, this->vertexNormals); - this->vertex_push_colour (col, this->vertexColors); - } - // Added 2*segments vertices to vertexPositions - - // After creating vertices, push all the indices. - for (std::int32_t j = 0; j < segments; j++) { - std::int32_t jn = (segments + ((j+1) % segments)) % segments; - this->indices.push_back (this->idx+(2*j)); - this->indices.push_back (this->idx+(2*jn)); - this->indices.push_back (this->idx+(2*jn+1)); - this->indices.push_back (this->idx+(2*j)); - this->indices.push_back (this->idx+(2*jn+1)); - this->indices.push_back (this->idx+(2*j+1)); - } - this->idx += 2 * segments; // nverts - - } // end computeFlatCircleLine - - // Compute a flat line circle outline - void computeFlatCircleLine (sm::vec centre, sm::vec norm, float radius, - float linewidth, std::array col, std::int32_t segments = 128) - { - // circle in a plane defined by a point (v0 = vstart or vend) and a normal - // (v) can be found: Choose random vector vr. A vector inplane = vr ^ v. The - // unit in-plane vector is inplane.normalise. Can now use that vector in the - // plan to define a point on the circle. Note that this starting point on - // the circle is at a random position, which means that this version of - // computeFlatCircleLine is useful for tubes that have quite a few segments. - sm::vec rand_vec; - rand_vec.randomize(); - sm::vec inplane = rand_vec.cross(norm); - // Sub call to the method that takes a normal vector AND an inplane vector: - this->computeFlatCircleLine (centre, norm, inplane, radius, linewidth, col, segments); - } - - // Compute triangles to form a true cuboid from 8 corners. - void computeCuboid (const std::array, 8>& v, const std::array& clr) - { - this->computeFlatQuad (v[0], v[1], v[2], v[3], clr); - this->computeFlatQuad (v[0], v[4], v[5], v[1], clr); - this->computeFlatQuad (v[1], v[5], v[6], v[2], clr); - this->computeFlatQuad (v[2], v[6], v[7], v[3], clr); - this->computeFlatQuad (v[3], v[7], v[4], v[0], clr); - this->computeFlatQuad (v[7], v[6], v[5], v[4], clr); - } - - // Compute a rhombus using the four defining coordinates. The coordinates are named as if - // they were the origin, x, y and z of a right-handed 3D coordinate system. These define three edges - void computeRhombus (const sm::vec& o, const sm::vec& x, const sm::vec& y, const sm::vec& z, - const std::array& clr) - { - // Edge vectors - sm::vec edge1 = x - o; - sm::vec edge2 = y - o; - sm::vec edge3 = z - o; - - // Compute the face normals - sm::vec _n1 = edge1.cross (edge2); - _n1.renormalize(); - sm::vec _n2 = edge2.cross (edge3); - _n2.renormalize(); - sm::vec _n3 = edge1.cross (edge3); - _n3.renormalize(); - - // Push positions and normals for 24 vertices to make up the rhombohedron; 4 for each face. - // Front face - this->vertex_push (o, this->vertexPositions); - this->vertex_push (o + edge1, this->vertexPositions); - this->vertex_push (o + edge3, this->vertexPositions); - this->vertex_push (o + edge1 + edge3, this->vertexPositions); - for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (_n3, this->vertexNormals); } - // Top face - this->vertex_push (o + edge3, this->vertexPositions); - this->vertex_push (o + edge1 + edge3, this->vertexPositions); - this->vertex_push (o + edge2 + edge3, this->vertexPositions); - this->vertex_push (o + edge2 + edge1 + edge3, this->vertexPositions); - for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (_n1, this->vertexNormals); } - // Back face - this->vertex_push (o + edge2 + edge3, this->vertexPositions); - this->vertex_push (o + edge2 + edge1 + edge3, this->vertexPositions); - this->vertex_push (o + edge2, this->vertexPositions); - this->vertex_push (o + edge2 + edge1, this->vertexPositions); - for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (-_n3, this->vertexNormals); } - // Bottom face - this->vertex_push (o + edge2, this->vertexPositions); - this->vertex_push (o + edge2 + edge1, this->vertexPositions); - this->vertex_push (o, this->vertexPositions); - this->vertex_push (o + edge1, this->vertexPositions); - for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (-_n1, this->vertexNormals); } - // Left face - this->vertex_push (o + edge2, this->vertexPositions); - this->vertex_push (o, this->vertexPositions); - this->vertex_push (o + edge2 + edge3, this->vertexPositions); - this->vertex_push (o + edge3, this->vertexPositions); - for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (-_n2, this->vertexNormals); } - // Right face - this->vertex_push (o + edge1, this->vertexPositions); - this->vertex_push (o + edge1 + edge2, this->vertexPositions); - this->vertex_push (o + edge1 + edge3, this->vertexPositions); - this->vertex_push (o + edge1 + edge2 + edge3, this->vertexPositions); - for (std::uint16_t i = 0U; i < 4U; ++i) { this->vertex_push (_n2, this->vertexNormals); } - - // Vertex colours are all the same - for (std::uint16_t i = 0U; i < 24U; ++i) { this->vertex_push_colour (clr, this->vertexColors); } - - // Indices for 6 faces - for (std::uint16_t i = 0U; i < 6U; ++i) { - this->indices.push_back (this->idx++); - this->indices.push_back (this->idx++); - this->indices.push_back (this->idx--); - this->indices.push_back (this->idx++); - this->indices.push_back (this->idx++); - this->indices.push_back (this->idx++); - } - } // computeCuboid - - // Compute a rectangular cuboid of width (in x), height (in y) and depth (in z). - void computeRectCuboid (const sm::vec& o, const float wx, const float hy, const float dz, - const std::array& clr) - { - sm::vec px = o + sm::vec{wx, 0, 0}; - sm::vec py = o + sm::vec{0, hy, 0}; - sm::vec pz = o + sm::vec{0, 0, dz}; - this->computeRhombus (o, px, py, pz, clr); - } - - // Compute the bounding box frame - void computeBoundingBox() - { - // Draw a frame of tubes from bb.min to bb.max - const float& x0 = this->bb.min[0]; - const float& y0 = this->bb.min[1]; - const float& z0 = this->bb.min[2]; - - const float& x1 = this->bb.max[0]; - const float& y1 = this->bb.max[1]; - const float& z1 = this->bb.max[2]; - - const sm::vec& c0 = this->bb.min; - sm::vec c1 = { x1, y0, z0 }; - sm::vec c2 = { x1, y1, z0 }; - sm::vec c3 = { x0, y1, z0 }; - - sm::vec c4 = { x0, y0, z1 }; - sm::vec c5 = { x1, y0, z1 }; - const sm::vec& c6 = this->bb.max; - sm::vec c7 = { x0, y1, z1 }; - - constexpr std::int32_t segs = 4; - constexpr float zrot = 0.0f; - auto cl = this->colour_bb; - - // Frame tube radius - float r = this->bb.span().length() / 500.0f; - - // Base - this->computeTube (c0, c1, sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - this->computeTube (c1, c2, -sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - this->computeTube (c2, c3, -sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - this->computeTube (c3, c0, sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - // Top - this->computeTube (c4, c5, sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - this->computeTube (c5, c6, -sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - this->computeTube (c6, c7, -sm::vec::uy(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - this->computeTube (c7, c4, sm::vec::ux(), sm::vec::uz(), cl, cl, r, segs, zrot, true); - // Sides - this->computeTube (c0, c4, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); - this->computeTube (c1, c5, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); - this->computeTube (c2, c6, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); - this->computeTube (c3, c7, sm::vec::uy(), -sm::vec::ux(), cl, cl, r, segs, zrot, true); - - // Oriented bounding box local axes/half-extents may be useful when debugging - constexpr bool show_obb_vectors = false; - if constexpr (show_obb_vectors) { - const sm::vec obb_centre = this->bb.mid(); - this->computeTube (obb_centre, obb_centre + this->bb_x, sm::vec::uy(), sm::vec::uz(), - cl, mplot::colour::crimson, r, segs, zrot, true); - this->computeTube (obb_centre, obb_centre + this->bb_y, sm::vec::uz(), sm::vec::ux(), - cl, mplot::colour::springgreen2, r, segs, zrot, true); - this->computeTube (obb_centre, obb_centre + this->bb_z, sm::vec::ux(), sm::vec::uy(), - cl, mplot::colour::blue2, r, segs, zrot, true); - } - } - }; - -} // namespace mplot diff --git a/mplot/VisualOwnable.cppm b/mplot/VisualOwnable.cppm deleted file mode 100644 index 4d029ad2..00000000 --- a/mplot/VisualOwnable.cppm +++ /dev/null @@ -1,2497 +0,0 @@ -/*! - * \file - * - * Awesome graphics code for high performance graphing and visualisation. - * - * This is intermediate class that sets up (multicontext aware) GL, leaving choice of window system - * (GLFW3/Qt/wx/etc) to a derived class such as mplot::Visual or mplot::qt::viswidget. - * - * This class is 'ownable', and can be used in other window drawing system such as Qt and wx, as - * well as within mplot::Visual, which marries it with the GLFW3 windowing system. - * - * Created by Seb James on 2025/03/01, from mplot::Visual.h - * - * \author Seb James - * \date March 2025 - */ -module; - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -export module mplot.visualownable; - -import mplot.version; -import mplot.visualmodel; -import mplot.win_t; -import mplot.visualcommon; -import mplot.visualresources; -import mplot.visualtextmodel; -import mplot.textgeometry; -import mplot.textfeatures; -import mplot.coordarrows; -import mplot.gl.version; -import mplot.gl.util; -import mplot.tools; -import mplot.loadpng; // Use Lode Vandevenne's PNG encoder -import mplot.keys; - -import sm.mathconst; -import sm.vec; -import sm.flags; -import sm.quaternion; -import sm.mat; - -export namespace mplot -{ - //! Here are our boolean state flags - enum class visual_state : std::uint32_t - { - readyToFinish, - //! paused can be set true so that pauseOpen() can be used to display the window mid-simulation - paused, - //! If you set this to true, then the mouse movements won't change scenetrans or rotation. - sceneLocked, - //! When true, cursor movements induce rotation of scene - rotateMode, - //! When true, rotations about the third axis are possible. - rotateModMode, - //! When true, cursor movements induce translation of scene - translateMode, - //! We are scrolling (and so we will need to zero scenetrans_delta after enacting the change) - scrolling, - //! True means that at least one of our VisualModels is an instanced rendering model - haveInstanced, - //! Left mouse button is down - mouseButtonLeftPressed, - //! Right mouse button is down - mouseButtonRightPressed, - //! If client code changes viewfollowsVMTranslations or viewFollowsVMBehind, this should be - //! set to signal to computeSceneview that the lastSceneview should be saved or restored to. - viewFollowsModeChanged, - //! Set true while the sceneview is 'zooming back' to the overview mode (or the whereever-you-left-it mode) - viewTransition, - //! Set true if we're in the middle of a scripted sceneview change, such as zooming in over a period of time - viewAutomation - }; - - //! Boolean options - similar to state, but more likely to be modified by client code - enum class visual_options : std::uint32_t - { - //! Set true to disable the 'X' button on the Window from exiting the program - preventWindowCloseWithButton, - //! Set to true to show the coordinate arrows - showCoordArrows, - //! If true, then place the coordinate arrows at the origin of the scene, rather than offset. - coordArrowsInScene, - //! Show user frame of reference (for debug) - showUserFrame, - //! Set to true to show the title text within the scene - showTitle, - //! Set true to output some user information to stdout (e.g. user requested quit) - userInfoStdout, - //! If true, output mplot version to stdout - versionStdout, - //! If true (the default), then call swapBuffers() at the end of render() - renderSwapsBuffers, - /*! - * If true, rotation is about the scene origin, rather than the most central VisualModel. - * - * If false, the system finds the most central VisualModel, and rotates about the centroid - * of the bounding box that surrounds that VisualModel. - */ - rotateAboutSceneOrigin, - /*! - * If true, horizontal mouse movements rotate the scene about a chosen vertical axis, and - * vertical mouse movements rotate the vertical axis about the bottom of the user's - * viewport. This will be familiar to Blender users. Additionally, if the ctrl-modified - * mouse move mode is enabled, the scene is tilted about the axis coming out of the - * viewport. - * - * If false, horizontal mouse movements rotate the scene about the vertical axis of the - * user's viewport, vertcial mouse movements rotate the scene about the horizontal axis of - * the viewport, and ctrl-modified mouse movements rotate the scene about the axis coming - * out of the viewport. This was the original scene navigation scheme in mathplot and before - * that in morphologica. - */ - rotateAboutVertical, - /*! - * If true, write bounding boxes out to a json file /tmp/mathplot_bounding_boxes.json that - * can be read with the show_boundingboxes program - */ - boundingBoxesToJson, - //! If true, draw all the bounding boxes around the VisualModels - showBoundingBoxes, - /*! - * If true, then turn on the bounding box for the VM about which we are rotating and turn - * the others off (ignoring the value of 'showBoundingBoxes') - */ - highlightRotationVM, - /*! - * If true, the view of the scene follows a model translation (one of the VisualModels in - * the scene has to be nominated as the 'model to follow'. Useful for top-down views. The - * selected model to follow is in a member attribute followedModel - */ - viewFollowsVMTranslations, - /*! - * The view 'camera' rotates with the selected VM (followedModel) - */ - viewFollowsVMBehind - }; - - //! Whether to render with perspective or orthographic - enum class perspective_type : std::uint32_t - { - perspective, - orthographic - }; - - //! Automated sceneview transforms, i.e. 'film direction' events. enumerated type of event. - enum class direction_event : std::uint32_t - { - sceneview, - timed_translation, - timed_rotation, - timed_transform, // Move towards a given sceneview - timed_orbit, // Starting from any sceneview, orbit a point - unknown - }; - - //! Automated sceneview transforms, i.e. 'film direction' events. This holds the data for an event. - struct direction_data - { - direction_event event = direction_event::unknown; - // a sceneview to move to, either instantaneously, or over a period of time - sm::mat sceneview = sm::mat::identity(); - sm::vec translation = {}; // A translation to apply to sceneview over time transform_time - sm::vec orbit_centre = {}; // Centre of the orbit for timed_orbit - sm::vec orbit_axis = sm::vec::uz(); - float orbit_angle = sm::mathconst::pi; - sm::quaternion rotation_start;// Holds the rotation of the sceneview at the start of the transform - sm::quaternion rotation; // A rotation of sceneview to achieve over time transform_time. - float about_vert_angle = 0.0f; // A rotation about the scene's up axis (in degrees) - float tilt_angle = 0.0f; - bool min_jerk = true; // Should the movement be minimum jerk, or linear? - std::uint32_t transform_time_frames = 0u; // Specify transform time in frames - std::uint32_t start_frame = std::numeric_limits::max(); - std::uint32_t id = std::numeric_limits::max(); // An ID for this direction (could be tied to movement frame) - }; - - /*! - * VisualOwnable - An ownable 'scene' base class. - * - * This class assumes that GL functions have been loaded by the GLAD header system as a - * GladGLContext pointer, which is called glfn here. GL function calls are glfn->Clear for - * Clear() and glfn->Enable() for Enable() and so on. - * - * \tparam glver The OpenGL version, encoded as a single int (see mplot::gl::version) - */ - template - class VisualOwnable - { - public: - /*! - * Default constructor is used when incorporating Visual inside another object - * such as a QWidget. We have to wait on calling init functions until an OpenGL - * environment is guaranteed to exist. - */ - VisualOwnable() - { - this->sceneview.translate (this->scenetrans_default); - this->sceneview_tr.translate (this->scenetrans_default); - } - - /*! - * Construct a new visualiser. The rule is 1 window to one Visual object. So, this creates a - * new window and a new OpenGL context. - */ - VisualOwnable (const std::int32_t _width, const std::int32_t _height, const std::string& _title, const bool _version_stdout = true) - { - this->sceneview.translate (this->scenetrans_default); - this->sceneview_tr.translate (this->scenetrans_default); - this->window_w = _width; - this->window_h = _height; - this->title = _title; - this->options.set (visual_options::versionStdout, _version_stdout); - this->init_gl(); - } - - ~VisualOwnable() {} - - //! Deconstruct gl memory/context - void deconstructCommon() - { - // Explicitly deconstruct any owned VisualModels - this->vm.clear(); - // Explicitly deconstruct coordArrows, textModel and texts here - this->coordArrows.reset (nullptr); - this->textModel.reset (nullptr); - for (std::uint32_t i = 0; i < this->texts.size(); ++i) { this->texts[i].reset (nullptr); } - //for (auto& t : this->texts) { t.reset (nullptr); } - - if (this->shaders.gprog) { - this->glfn->DeleteProgram (this->shaders.gprog); - this->shaders.gprog = 0; - } - if (this->shaders.tprog) { - this->glfn->DeleteProgram (this->shaders.tprog); - this->shaders.tprog = 0; - } - this->free_gladgl_context (this->glfn); - - // Free up the Fonts associated with this mplot::Visual - mplot::VisualResources::i().freetype_deinit (this->visual_id); - } - - // Public init that is given a context (window or widget) and then sets up the - // VisualResource, shaders and so on. - void init (mplot::win_t* ctx) - { - this->window = ctx; - this->init_resources(); - this->init_gl(); - } - - // Do one-time init of the Visual's resources. This gets/creates the VisualResources, - // registers this visual with resources, calls init_window for any glfw stuff that needs to - // happen, and lastly initializes the freetype code. - void init_resources() - { - // VisualResources provides font management and GLFW management. Ensure it exists in memory. - mplot::VisualResources::i().create(); - this->visual_id = mplot::VisualResources::i().register_visual (this->glfn, this->window); - mplot::VisualResources::i().freetype_init (this->visual_id, this->glfn); - } - - /*! - * Add a VisualModel to the scene as a unique_ptr. The Visual object takes ownership of the - * unique_ptr. The index into Visual::vm is returned. - */ - template - std::uint32_t addVisualModelId (std::unique_ptr& model) - { - std::unique_ptr> vmp = std::move(model); - vmp->set_parent (this->visual_id); - if (vmp->instanced()) { this->state.set (visual_state::haveInstanced, true); } - this->vm.push_back (std::move(vmp)); - std::uint32_t rtn = (this->vm.size()-1); - return rtn; - } - - /*! - * Add a VisualModel to the scene as a unique_ptr. The Visual object takes ownership of the - * unique_ptr. A non-owning pointer to the model is returned. - */ - template - T* addVisualModel (std::unique_ptr& model) - { - std::unique_ptr> vmp = std::move(model); - vmp->set_parent (this->visual_id); - if (vmp->instanced()) { this->state.set (visual_state::haveInstanced, true); } - this->vm.push_back (std::move(vmp)); - return static_cast(this->vm.back().get()); - } - - /*! - * Test the pointer vmp. Return vmp if it is owned by a unique_ptr in - * Visual::vm. If it is not present, return nullptr. - */ - const mplot::VisualModel* validVisualModel (const mplot::VisualModel* vmp) const - { - const mplot::VisualModel* rtn = nullptr; - for (std::uint32_t modelId = 0; modelId < this->vm.size(); ++modelId) { - if (this->vm[modelId].get() == vmp) { - rtn = vmp; - break; - } - } - return rtn; - } - - /*! - * For the pointer vmp, if it is owned by a unique_ptr in Visual::vm, then return the index - * into Visual::vm at which it lives. This is its model ID. If it does not exist in - * Visual::vm, then return std::numeric_limits::max(). - */ - std::uint32_t getVisualModelId (const mplot::VisualModel* vmp) const - { - std::uint32_t rtn = std::numeric_limits::max(); - for (std::uint32_t modelId = 0; modelId < this->vm.size(); ++modelId) { - if (this->vm[modelId].get() == vmp) { - rtn = modelId; - break; - } - } - return rtn; - } - - void setFollowedVM (const mplot::VisualModel* vm_to_follow) - { - for (std::uint32_t modelId = 0; modelId < this->vm.size(); ++modelId) { - if (this->vm[modelId].get() == vm_to_follow) { - this->followedVM = this->vm[modelId].get(); - this->followedLastViewMatrix = this->followedVM->getViewMatrix(); - break; - } - } - } - - /*! - * VisualModel Getter - * - * For the given \a modelId, return a (non-owning) pointer to the visual model. - * - * \return VisualModel pointer - */ - mplot::VisualModel* getVisualModel (std::uint32_t modelId) { return (this->vm[modelId].get()); } - - //! Remove the VisualModel with ID \a modelId from the scene. - void removeVisualModel (std::uint32_t modelId) { this->vm.erase (this->vm.begin() + modelId); } - - //! Remove the VisualModel whose pointer matches the VisualModel* vmp - void removeVisualModel (mplot::VisualModel* vmp) - { - std::uint32_t modelId = 0; - bool found_model = false; - for (modelId = 0; modelId < this->vm.size(); ++modelId) { - if (this->vm[modelId].get() == vmp) { - found_model = true; - break; - } - } - if (found_model == true) { this->vm.erase (this->vm.begin() + modelId); } - } - - //! Remove the VisualModels in the vm stack from the one whose pointer matches the - //! VisualModel* vmp, to the end of the stack. - void removeVisualModels (mplot::VisualModel* vmp) - { - std::uint32_t modelId = 0; - bool found_model = false; - for (modelId = 0; modelId < this->vm.size(); ++modelId) { - if (this->vm[modelId].get() == vmp) { - found_model = true; - break; - } - } - if (found_model == true) { this->vm.erase (this->vm.begin() + modelId, this->vm.end()); } - } - - void clear () { this->vm.clear(); } - - void set_cursorpos (double _x, double _y) { this->cursorpos = {static_cast(_x), static_cast(_y)}; } - - //! A callback function - static void callback_render (mplot::VisualOwnable* _v) { _v->render(); }; - - //! GLAD OpenGL function context pointer. A copy is stored in VisualResources. - GladGLContext* glfn = nullptr; - - //! Stores the OpenGL function context version that was loaded - std::int32_t glfn_version = 0; - - //! Graphics context functions that refer to the window system (GLFW usually) are defined in derived class - virtual void setContext() = 0; - virtual void releaseContext() = 0; - virtual void swapBuffers() = 0; - virtual void setSwapInterval() = 0; - - //! Take a screenshot of the window. Return vec containing width * height or {-1, -1} on - //! failure. Set transparent_bg to get a transparent background. - sm::vec saveImage (const std::string& img_filename, const bool transparent_bg = false) - { - using namespace std::chrono; - using sc = std::chrono::steady_clock; - constexpr bool profile_saveimage = false; - sc::time_point t0, t1, t2; - - this->setContext(); - - if constexpr (profile_saveimage) { t0 = sc::now(); } - - std::int32_t viewport[4]; // current viewport - this->glfn->GetIntegerv (GL_VIEWPORT, viewport); - - sm::vec dims; - dims[0] = viewport[2]; - dims[1] = viewport[3]; - auto bits = std::make_unique(dims.product() * 4); - auto rbits = std::make_unique(dims.product() * 4); - - this->glfn->Finish(); // finish all commands of OpenGL - this->glfn->PixelStorei (GL_PACK_ALIGNMENT, 1); - this->glfn->PixelStorei (GL_PACK_ROW_LENGTH, 0); - this->glfn->PixelStorei (GL_PACK_SKIP_ROWS, 0); - this->glfn->PixelStorei (GL_PACK_SKIP_PIXELS, 0); - this->glfn->ReadPixels (0, 0, dims[0], dims[1], GL_RGBA, GL_UNSIGNED_BYTE, bits.get()); - - for (std::int32_t i = 0; i < dims[1]; ++i) { - std::int32_t rev_line = (dims[1] - i - 1) * 4 * dims[0]; - std::int32_t for_line = i * 4 * dims[0]; - if (transparent_bg) { - for (std::int32_t j = 0; j < 4 * dims[0]; ++j) { - rbits[rev_line + j] = bits[for_line + j]; - } - } else { - for (std::int32_t j = 0; j < 4 * dims[0]; ++j) { - rbits[rev_line + j] = (j % 4 == 3) ? 255 : bits[for_line + j]; - } - } - } - - if constexpr (profile_saveimage) { t1 = sc::now(); } - - std::uint32_t error = 0; - - // If filename ends with pnm, then save in pnm format; otherwise save as PNG - bool pnm_save = false; - if (img_filename.find ("pnm") == img_filename.size() - 3) { pnm_save = true; } - if (pnm_save == true) { - error = mplot::pnm_encode (img_filename, rbits.get(), dims[0], dims[1]); - } else { - error = mplot::png_encode (img_filename, rbits.get(), dims[0], dims[1]); // Need alternative - } - - if constexpr (profile_saveimage) { - t2 = sc::now(); - sc::duration t_d = t1 - t0; - sc::duration t_d2 = t2 - t1; - std::cout << "Bit-collection: " << duration_cast(t_d).count() << " ms" - << " and png/pnm_encode: " << duration_cast(t_d2).count() << " ms\n"; - } - - if (error) { - if (pnm_save == true) { - std::cerr << "pnm encoder error " << error << std::endl; - } else { - std::cerr << "encoder error " << error << ": " << mplot::png_error_text (error) << std::endl; - } - dims.set_from (-1); - return dims; - } - return dims; - } - - //! Render the scene - void render() noexcept - { - ++this->render_counter; - - this->setContext(); - - this->glfn->UseProgram (this->shaders.gprog); - this->glfn->Viewport (0, 0, this->window_w * this->window_scale_w, this->window_h * this->window_scale_h); - - // Set the perspective - if (this->ptype == perspective_type::orthographic) { - this->setOrthographic(); - } else if (this->ptype == perspective_type::perspective) { - this->setPerspective(); - } else { - // unknown projection - return; - } - - // Calculate model view transformation - transforming from "model space" to "worldspace". - this->computeSceneview(); - - // Clear color buffer and **also depth buffer** - this->glfn->Clear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - // Set the background colour: - this->glfn->ClearBufferfv (GL_COLOR, 0, this->bgcolour.data()); - - // Lighting shader variables - // - // Ambient light colour - GLint loc_lightcol = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("light_colour")); - if (loc_lightcol != -1) { this->glfn->Uniform3fv (loc_lightcol, 1, this->light_colour.data()); } - // Ambient light intensity - GLint loc_ai = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("ambient_intensity")); - if (loc_ai != -1) { this->glfn->Uniform1f (loc_ai, this->ambient_intensity); } - // Diffuse light position - GLint loc_dp = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("diffuse_position")); - if (loc_dp != -1) { this->glfn->Uniform3fv (loc_dp, 1, this->diffuse_position.data()); } - // Diffuse light intensity - GLint loc_di = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("diffuse_intensity")); - if (loc_di != -1) { this->glfn->Uniform1f (loc_di, this->diffuse_intensity); } - - // Switch to text shader program and set the projection matrix - this->glfn->UseProgram (this->shaders.tprog); - GLint loc_p = this->glfn->GetUniformLocation (this->shaders.tprog, static_cast("p_matrix")); - if (loc_p != -1) { this->glfn->UniformMatrix4fv (loc_p, 1, GL_FALSE, this->projection.arr.data()); } - - // Switch back to the regular shader prog and render the VisualModels. - this->glfn->UseProgram (this->shaders.gprog); - - // Set the projection matrix just once - loc_p = this->glfn->GetUniformLocation (this->shaders.gprog, static_cast("p_matrix")); - if (loc_p != -1) { this->glfn->UniformMatrix4fv (loc_p, 1, GL_FALSE, this->projection.arr.data()); } - - if ((this->ptype == perspective_type::orthographic || this->ptype == perspective_type::perspective) - && this->options.test (visual_options::showCoordArrows)) { - // Ensure coordarrows centre sphere will be visible on BG: - this->coordArrows->setColourForBackground (this->bgcolour); // releases context... - this->setContext(); // ...so re-acquire if we're managing it - - if (this->options.test (visual_options::coordArrowsInScene) == true) { - this->coordArrows->setSceneMatrix (this->sceneview); - } else { - this->positionCoordArrows(); - } - this->coordArrows->render(); - } - - if (this->haveInstanced() && mplot::VisualResources::i().get_instanced_needs_update (this->visual_id)) { - mplot::VisualResources::i().copy_instance_ssbo_to_gpu(); - mplot::VisualResources::i().instanced_needs_update (this->visual_id, false); - } - - auto vmi = this->vm.begin(); - while (vmi != this->vm.end()) { - if ((*vmi)->twodimensional() == true) { - // It's a two-d thing. Use the companion 'scene trans only' matrix, which avoids any rotations - (*vmi)->setSceneMatrix (this->sceneview_tr); - } else { - (*vmi)->setSceneMatrix (this->sceneview); - } - (*vmi)->render(); - ++vmi; - } - - sm::vec v0 = this->textPosition ({-0.8f, 0.8f}); - if (this->options.test (visual_options::showTitle) == true) { - // Render the title text - this->textModel->setSceneTranslation (v0); - this->textModel->setVisibleOn (this->bgcolour); - this->textModel->render(); - } - - auto ti = this->texts.begin(); - while (ti != this->texts.end()) { - (*ti)->setSceneTranslation (v0); - (*ti)->setVisibleOn (this->bgcolour); - (*ti)->render(); - ++ti; - } - - if (this->options.test (visual_options::renderSwapsBuffers) == true) { - this->swapBuffers(); - } - } - - //! Compute a translation vector for text position, using Visual::text_z. - sm::vec textPosition (const sm::vec p0_coord) - { - // For the depth at which a text object lies, use this->text_z. Use forward - // projection to determine the correct z coordinate for the inverse - // projection. - sm::vec point = { 0.0f, 0.0f, this->text_z, 1.0f }; - sm::vec pp = this->projection * point; - float coord_z = pp[2]/pp[3]; // divide by pp[3] is divide by/normalise by 'w'. - // Construct the point for the location of the text - sm::vec p0 = { p0_coord.x(), p0_coord.y(), coord_z, 1.0f }; - // Inverse project the point - sm::vec v0; - v0.set_from (this->invproj * p0); - return v0; - } - - protected: - // GLAD specific gl context creation/freeing. GladGLContext is a struct containing - GladGLContext* create_gladgl_context (const GLADloadfunc procaddressfn) - { - GladGLContext* context = (GladGLContext*) calloc(1, sizeof(GladGLContext)); - if (!context) { return nullptr; } - this->glfn_version = gladLoadGLContext (context, procaddressfn); - // ...so glfn_version should (more or less) match the version specified in the glver - // template arg - return context; - } - void free_gladgl_context (GladGLContext *context) - { - if (context) { free(context); } - context = nullptr; - } - - public: - void init_glad (GLADloadfunc procaddressfn) - { - // Create the OpenGL function context - a GladGLContext* - this->glfn = this->create_gladgl_context (procaddressfn); - - if (!this->glfn) { - std::cout << "Failed to initialize GLAD GL context" << std::endl; - this->free_gladgl_context (this->glfn); - } - } - - //! Add a label _text to the scene at position _toffset. Font features are - //! defined by the tf. Return geometry of the text. - mplot::TextGeometry addLabel (const std::string& _text, - const sm::vec& _toffset, - const mplot::TextFeatures& tf = mplot::TextFeatures(0.01f)) - { - this->setContext(); - if (this->shaders.tprog == 0) { throw std::runtime_error ("No text shader prog."); } - auto tmup = std::make_unique> (tf); - tmup->set_parent (this->visual_id); - if (tf.centre_horz == true) { - mplot::TextGeometry tg = tmup->getTextGeometry(_text); - sm::vec centred_locn = _toffset; - centred_locn[0] = -tg.half_width(); - tmup->setupText (_text, centred_locn, tf.colour); - } else { - tmup->setupText (_text, _toffset, tf.colour); - } - mplot::VisualTextModel* tm = tmup.get(); - this->texts.push_back (std::move(tmup)); - this->releaseContext(); - return tm->getTextGeometry(); - } - - //! Add a label _text to the scene at position _toffset. Font features are - //! defined by the tf. Return geometry of the text. The pointer tm is a - //! return value that allows client code to change the text after the label has been added. - mplot::TextGeometry addLabel (const std::string& _text, - const sm::vec& _toffset, - mplot::VisualTextModel*& tm, - const mplot::TextFeatures& tf = mplot::TextFeatures(0.01f)) - { - this->setContext(); - if (this->shaders.tprog == 0) { throw std::runtime_error ("No text shader prog."); } - auto tmup = std::make_unique> (tf); - tmup->set_parent (this->visual_id); - if (tf.centre_horz == true) { - mplot::TextGeometry tg = tmup->getTextGeometry(_text); - sm::vec centred_locn = _toffset; - centred_locn[0] = -tg.half_width(); - tmup->setupText (_text, centred_locn, tf.colour); - } else { - tmup->setupText (_text, _toffset, tf.colour); - } - tm = tmup.get(); - this->texts.push_back (std::move(tmup)); - this->releaseContext(); - return tm->getTextGeometry(); - } - - protected: - // Initialize OpenGL shaders, set some flags (Alpha, Anti-aliasing) and set up the - // coordinate arrows and any VisualTextModels that will be required to render the Visual. - void init_gl() - { - this->setContext(); // if managing context - - if (this->options.test (visual_options::versionStdout) == true) { - std::uint8_t* glv = (std::uint8_t*)this->glfn->GetString(GL_VERSION); - std::cout << "This is version " << mplot::version_string() - << " of mplot::Visual running on OpenGL Version " << glv << std::endl; - } - - this->setSwapInterval(); - - // Load up the shaders - this->proj2d_shader_progs = { - {GL_VERTEX_SHADER, "Visual.vert.glsl", mplot::getDefaultVtxShader(glver), 0 }, - {GL_FRAGMENT_SHADER, "Visual.frag.glsl", mplot::getDefaultFragShader(glver), 0 } - }; - this->shaders.gprog = mplot::gl::LoadShadersMX (this->proj2d_shader_progs, this->glfn); - mplot::VisualResources::i().set_gprog (this->visual_id, this->shaders.gprog); - - // A specific text shader is loaded for text rendering - this->text_shader_progs = { - {GL_VERTEX_SHADER, "VisText.vert.glsl", mplot::getDefaultTextVtxShader(glver), 0 }, - {GL_FRAGMENT_SHADER, "VisText.frag.glsl" , mplot::getDefaultTextFragShader(glver), 0 } - }; - this->shaders.tprog = mplot::gl::LoadShadersMX (this->text_shader_progs, this->glfn); - mplot::VisualResources::i().set_tprog (this->visual_id, this->shaders.tprog); - - // OpenGL options - this->glfn->Enable (GL_DEPTH_TEST); - this->glfn->Enable (GL_BLEND); - this->glfn->BlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - this->glfn->Disable (GL_CULL_FACE); - mplot::gl::Util::checkError (__FILE__, __LINE__, this->glfn); - - // Use coordArrowsOffset to set the location of the CoordArrows *scene* - this->coordArrows = std::make_unique>(); - this->coordArrows->set_parent (this->visual_id); - // And NOW we can proceed to init (lengths, thickness, em size for labels): - this->coordArrows->init (sm::vec<>{0.1f, 0.1f, 0.1f}, 1.0f, 0.01f); - this->coordArrows->finalize(); // VisualModel::finalize releases context (normally this is the right thing)... - this->setContext(); // ...but we've got more work to do, so re-acquire context (if we're managing it) - - mplot::gl::Util::checkError (__FILE__, __LINE__, this->glfn); - - // Set up the title, which may or may not be rendered - mplot::TextFeatures title_tf(0.035f, 64); - this->textModel = std::make_unique> (title_tf); - this->textModel->set_parent (this->visual_id); - this->textModel->setSceneTranslation ({0.0f, 0.0f, 0.0f}); - this->textModel->setupText (this->title); - - this->releaseContext(); - } - - //! A VisualTextModel for a title text. - std::unique_ptr> textModel = nullptr; - //! Text models for labels - std::vector>> texts; - - public: - //! The OpenGL shader programs have an integer ID and are stored in a simple struct. There's - //! one for graphical objects and a text shader program, which uses textures to draw text on - //! quads. - mplot::visgl::visual_shaderprogs shaders; // stored in VisualResources too. - - //! Stores the info required to load the 2D projection shader - std::vector proj2d_shader_progs; - //! Stores the info required to load the text shader - std::vector text_shader_progs; - - //! The colour of ambient and diffuse light sources - sm::vec light_colour = { 1.0f, 1.0f, 1.0f }; - //! Strength of the ambient light - float ambient_intensity = 1.0f; - //! Position of a diffuse light source - sm::vec diffuse_position = { 5.0f, 5.0f, 15.0f }; - //! Strength of the diffuse light source - float diffuse_intensity = 0.0f; - - // Track how many calls to render have been made. At 1000 FPS this overflows at 10^17 seconds which is about 10^9 years. - std::uint64_t render_counter = 0u; - // A move counter. May be incremented in step with render_counter, or it may not (for example, it may restart) - std::uint64_t move_counter = 0u; - - //! Compute position and rotation of coordinate arrows in the bottom left of the screen - void positionCoordArrows() - { - // Find out the location of the bottom left of the screen and make the coord - // arrows stay put there. - - // Add the depth at which the object lies. Use forward projection to determine the - // correct z coordinate for the inverse projection. This assumes only one object. - sm::vec point = { 0.0f, 0.0f, this->sceneview[14], 1.0f }; // sceneview[14] is 'scenetrans.z' - sm::vec pp = this->projection * point; - float coord_z = pp[2]/pp[3]; // divide by pp[3] is divide by/normalise by 'w'. - - // Construct the point for the location of the coord arrows - sm::vec p0 = { this->coordArrowsOffset.x(), this->coordArrowsOffset.y(), coord_z, 1.0f }; - // Inverse project - sm::vec v0; - v0.set_from ((this->invproj * p0)); - // Translate the scene for the CoordArrows such that they sit in a single position on - // the screen - this->coordArrows->setSceneTranslation (v0); - // Apply rotation to the coordArrows model - sm::quaternion svrq = this->sceneview.rotation(); - svrq.renormalize(); - this->coordArrows->setViewRotation (svrq); - } - - // Update the coordinate axes labels - void updateCoordLabels (const std::string& x_lbl, const std::string& y_lbl, const std::string& z_lbl) - { - this->coordArrows->clear(); - this->coordArrows->x_label = x_lbl; - this->coordArrows->y_label = y_lbl; - this->coordArrows->z_label = z_lbl; - this->coordArrows->initAxisLabels(); - this->coordArrows->reinit(); - } - - // Update the lengths of the CoordArrows that (usually) appear in the corner of the screen - void updateCoordLengths (const sm::vec& _lengths, const float _thickness = 1.0f) - { - this->coordArrows->lengths = _lengths; - this->coordArrows->thickness = _thickness; - this->coordArrows->clear(); - this->coordArrows->initAxisLabels(); - this->coordArrows->reinit(); - } - - // state defaults. All state is false by default - constexpr sm::flags state_defaults() - { - sm::flags _state; - return _state; - } - - // State flags - sm::flags state = state_defaults(); - - // Options defaults. - constexpr sm::flags options_defaults() - { - sm::flags _options; - // Only with ImGui do we manually swap buffers, so this is true by default: - _options.set (visual_options::renderSwapsBuffers); - // For now, default to rotating about scene origin, as we ever did (Ctrl-k to change) - _options.set (visual_options::rotateAboutSceneOrigin); - // Also, for now, keep the Blender-like 'rotateAboutVertical' as a non-default option (Ctrl-d to change) - _options.set (visual_options::rotateAboutVertical, false); - - return _options; - } - - // Option flags - sm::flags options = options_defaults(); - - //! Returns true when the program has been flagged to end - bool readyToFinish() const { return this->state.test (visual_state::readyToFinish); } - - //! Returns true if we are in the paused state - bool paused() const { return this->state.test (visual_state::paused); } - - //! True if one of our added VisualModels is an instanced model - bool haveInstanced() const { return this->state.test (visual_state::haveInstanced); } - - /* - * User-settable projection values for the near clipping distance, the far clipping distance - */ - float zNear = 0.001f; - float zFar = 300.0f; - - /* - * User settable field of view of the camera in degrees. Note that the field of view is - * measured from the top of the field to the bottom of the field (rather than from the left - * to the right). - */ - float fov = 30.0f; - - //! Setter for fov - void set_vertical_fov (const float vfov) { this->fov = vfov; } - //! Setter for fov, if you want to specify horizontal field of view - void set_horizontal_fov (const float hfov) - { - float aspect = static_cast(this->window_w) / static_cast(this->window_h ? this->window_h : 1); - this->fov = hfov / aspect; - } - - //! Time constants for the way the camera moves between a follow-me view and a - //! drone-view. One for translation, the other for rotation. - float trans_tc = 0.09f; - //! Rotational time constant - float rotn_tc = trans_tc; - - //! Which was is up in the scene? In OpenGL it's usually y, but may be changed to z in some cases - sm::vec scene_up = sm::vec::uy(); - //! Which way goes to the 'right' across the screen? Usually x - sm::vec scene_right = sm::vec::ux(); - //! Out of the screen? - sm::vec scene_out = sm::vec::uz(); - - //! Setter for visual_options::showCoordArrows - void showCoordArrows (const bool val) { this->options.set (visual_options::showCoordArrows, val); } - - //! If true, then place the coordinate arrows at the origin of the scene, rather than offset. - void coordArrowsInScene (const bool val) { this->options.set (visual_options::coordArrowsInScene, val); } - - //! Rotate about the nearest VisualModel? - void rotateAboutNearest (const bool val) - { this->options.set (mplot::visual_options::rotateAboutSceneOrigin, (val ? false : true)); } - - //! Rotate about a vertical axis in the scene? - void rotateAboutVertical (const bool val) { this->options.set (visual_options::rotateAboutVertical, val); } - - //! Set to true to show the title text within the scene - void showTitle (const bool val) { this->options.set (visual_options::showTitle, val); } - - //! Set true to output some user information to stdout (e.g. user requested quit) - void userInfoStdout (const bool val) { this->options.set (visual_options::userInfoStdout, val); } - - //! You can call this with val==false to manage exactly when you call the swapBuffer() method (for ImGui programs) - void renderSwapsBuffers (const bool val) { this->options.set (visual_options::renderSwapsBuffers, val); } - - //! How big should the steps in scene translation be when scrolling? - float scenetrans_stepsize = 0.02f; - - //! If you set this to true, then the mouse movements won't change scenetrans or rotation. - void sceneLocked (const bool val) { this->state.set (visual_state::sceneLocked, val); } - - //! Show bounding boxes? - void showBoundingBoxes (const bool val) { this->options.set (visual_options::showBoundingBoxes, val); } - - //! Highlight (with a bounding box) the VisualModel being used for rotation? - void highlightRotationVM (const bool val) { this->options.set (visual_options::highlightRotationVM, val); } - - //! Can change this to orthographic - perspective_type ptype = perspective_type::perspective; - - //! Orthographic screen left-bottom coordinate (you can change these to encapsulate your models) - sm::vec ortho_lb = { -1.3f, -1.0f }; - //! Orthographic screen right-top coordinate - sm::vec ortho_rt = { 1.3f, 1.0f }; - - //! The background colour; white by default. - std::array bgcolour = { 1.0f, 1.0f, 1.0f, 0.5f }; - - /* - * User can directly set bgcolour for any background colour they like, but - * here are convenience functions: - */ - - //! Set a white background colour for the Visual scene - void backgroundWhite() { this->bgcolour = { 1.0f, 1.0f, 1.0f, 0.5f }; } - //! Set a black background colour for the Visual scene - void backgroundBlack() { this->bgcolour = { 0.0f, 0.0f, 0.0f, 0.0f }; } - - //! Set sceneview and sceneview_tr back to scenetrans_default - void reset_sceneviews_to_scenetrans_default() - { - this->sceneview.set_identity(); - this->sceneview.translate (this->scenetrans_default); - this->sceneview_tr.set_identity(); - this->sceneview_tr.translate (this->scenetrans_default); - this->d_to_rotation_centre = -this->scenetrans_default[2]; - } - - void setSceneview (const sm::mat& sv) - { - this->lastSceneview = this->sceneview; - this->sceneview = sv; - this->sceneview_tr.set_identity(); - this->sceneview_tr.translate (sv.translation()); - } - - //! Set the scene's x and y values at the same time. - void setSceneTransXY (const float _x, const float _y) - { - this->scenetrans_default[0] = _x; - this->scenetrans_default[1] = _y; - this->reset_sceneviews_to_scenetrans_default(); - } - //! Set the scene's y value. Use this to shift your scene objects left or right - void setSceneTransX (const float _x) - { - this->scenetrans_default[0] = _x; - this->reset_sceneviews_to_scenetrans_default(); - } - //! Set the scene's y value. Use this to shift your scene objects up and down - void setSceneTransY (const float _y) - { - this->scenetrans_default[1] = _y; - this->reset_sceneviews_to_scenetrans_default(); - } - //! Set the scene's z value. Use this to bring the 'camera' closer to your scene - //! objects (that is, your mplot::VisualModel objects). - void setSceneTransZ (const float _z) - { - if (_z > 0.0f) { - std::cerr << "WARNING setSceneTransZ(): Normally, the default z value is negative.\n"; - } - this->scenetrans_default[2] = _z; - this->reset_sceneviews_to_scenetrans_default(); - } - void setSceneTrans (float _x, float _y, float _z) - { - if (_z > 0.0f) { - std::cerr << "WARNING setSceneTrans(): Normally, the default z value is negative.\n"; - } - - this->scenetrans_default[0] = _x; - this->scenetrans_default[1] = _y; - this->scenetrans_default[2] = _z; - this->reset_sceneviews_to_scenetrans_default(); - } - void setSceneTrans (const sm::vec& _xyz) - { - if (_xyz[2] > 0.0f) { - std::cerr << "WARNING setSceneTrans(vec<>&): Normally, the default z value is negative.\n"; - } - this->scenetrans_default = _xyz; - this->reset_sceneviews_to_scenetrans_default(); - } - - void setSceneRotation (const sm::quaternion& _rotn) - { - this->rotation_default = _rotn; - this->sceneview.rotate (_rotn); - } - - // What is the scene view's current rotation quaternion? - sm::quaternion getSceneRotation() const { return this->sceneview.rotation(); } - // What is the scene view's current translation? - sm::vec getSceneTranslation() const { return this->sceneview.translation(); } - - // API for client code to set a 'film direction' event. This may change the sceneview - // immediately, or start a timed sequence of changes to animate the sceneview. - void setCurrentDirectionEvent (const mplot::direction_data& dirn) - { - constexpr bool debug_dirn_event = false; - - // timed translation/rotation/transform are all 'viewAutomations' - this->state.set (visual_state::viewAutomation); - this->currentAutoSceneviewChange = dirn; - this->currentAutoSceneviewChange.start_frame = this->render_counter; - if constexpr (debug_dirn_event) { - std::cout << __func__ << " event id " << this->currentAutoSceneviewChange.id - << " starting at frame " << this->currentAutoSceneviewChange.start_frame << std::endl; - } - // Auto translation behaves like a mouse-press then mouse-drag; computing a delta from a savedSceneview - this->savedSceneview = this->sceneview; - this->savedSceneview_tr = this->sceneview_tr; - this->scenetrans_delta.zero(); - this->rotation_delta.reset(); - // If it's a rotation event, also need a rotation centre - if (dirn.event == direction_event::timed_rotation) { - this->find_rotation_centre(); - } else if (dirn.event == direction_event::timed_transform) { - // Find the start and end translation - this->currentAutoSceneviewChange.translation = dirn.sceneview.translation() - this->sceneview.translation(); - // Find the start and end rotation - this->currentAutoSceneviewChange.rotation_start = this->sceneview.rotation(); // rotation at start - this->currentAutoSceneviewChange.rotation_start.renormalize(); - this->currentAutoSceneviewChange.rotation = dirn.sceneview.rotation(); // rotation at end - this->currentAutoSceneviewChange.rotation.renormalize(); - this->find_rotation_centre(); - } else if (dirn.event == direction_event::sceneview) { - std::cout << "Set a sceneview event for current direction event" << std::endl; - // An immediate sceneview event is just a timed_transform with the time for the transform set to 1 - this->currentAutoSceneviewChange.transform_time_frames = 2u; - this->currentAutoSceneviewChange.min_jerk = false; - // Find the start and end translation - this->currentAutoSceneviewChange.translation = dirn.sceneview.translation() - this->sceneview.translation(); - // Find the start and end rotation - this->currentAutoSceneviewChange.rotation_start = this->sceneview.rotation(); // rotation at start - this->currentAutoSceneviewChange.rotation_start.renormalize(); - this->currentAutoSceneviewChange.rotation = dirn.sceneview.rotation(); // rotation at end - this->currentAutoSceneviewChange.rotation.renormalize(); - this->find_rotation_centre(); - } else if (dirn.event == direction_event::timed_orbit) { - // Might need this: - this->currentAutoSceneviewChange.translation = dirn.sceneview.translation() - this->sceneview.translation(); - } - } - - void lightingEffects (const bool effects_on = true) - { - this->ambient_intensity = effects_on ? 0.4f : 1.0f; - this->diffuse_intensity = effects_on ? 0.6f : 0.0f; - } - - //! Save all the VisualModels in this Visual out to a GLTF format file - virtual void savegltf (const std::string& gltf_file) - { - std::ofstream fout (gltf_file, std::ios::out|std::ios::trunc); - if (!fout.is_open()) { throw std::runtime_error ("Visual::savegltf(): Failed to open file for writing"); } - fout << "{\n \"scenes\" : [ { \"nodes\" : [ "; - for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { - fout << vmi << (vmi < this->vm.size()-1 ? ", " : ""); - } - fout << " ] } ],\n"; - - fout << " \"nodes\" : [\n"; - // for loop over VisualModels "mesh" : 0, etc - for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { - fout << " { \"mesh\" : " << vmi - << ", \"translation\" : " << this->vm[vmi]->translation_str() - << (vmi < this->vm.size()-1 ? " },\n" : " }\n"); - } - fout << " ],\n"; - - fout << " \"meshes\" : [\n"; - // for each VisualModel: - for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { - fout << " { "; - if (!this->vm[vmi]->name.empty()) { - fout << "\"name\" : \"" << this->vm[vmi]->name << "\", "; - } - fout << "\"primitives\" : [ { \"attributes\" : { \"POSITION\" : " << 1+vmi*4 - << ", \"COLOR_0\" : " << 2+vmi*4 - << ", \"NORMAL\" : " << 3+vmi*4 << " }, \"indices\" : " << vmi*4 << ", \"material\": 0 } ] }" - << (vmi < this->vm.size()-1 ? ",\n" : "\n"); - } - fout << " ],\n"; - - fout << " \"buffers\" : [\n"; - for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { - // indices - fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->indices_base64() << "\", " - << "\"byteLength\" : " << this->vm[vmi]->indices_bytes() << "},\n"; - // pos - fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->vpos_base64() << "\", " - << "\"byteLength\" : " << this->vm[vmi]->vpos_bytes() << "},\n"; - // col - fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->vcol_base64() << "\", " - << "\"byteLength\" : " << this->vm[vmi]->vcol_bytes() << "},\n"; - // norm - fout << " {\"uri\" : \"data:application/octet-stream;base64," << this->vm[vmi]->vnorm_base64() << "\", " - << "\"byteLength\" : " << this->vm[vmi]->vnorm_bytes() << "}"; - fout << (vmi < this->vm.size()-1 ? ",\n" : "\n"); - } - fout << " ],\n"; - - fout << " \"bufferViews\" : [\n"; - for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { - // indices - fout << " { "; - fout << "\"buffer\" : " << vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - fout << "\"byteLength\" : " << this->vm[vmi]->indices_bytes() << ", "; - fout << "\"target\" : 34963 "; - fout << " },\n"; - // vpos - fout << " { "; - fout << "\"buffer\" : " << 1+vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - fout << "\"byteLength\" : " << this->vm[vmi]->vpos_bytes() << ", "; - fout << "\"target\" : 34962 "; - fout << " },\n"; - // vcol - fout << " { "; - fout << "\"buffer\" : " << 2+vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - fout << "\"byteLength\" : " << this->vm[vmi]->vcol_bytes() << ", "; - fout << "\"target\" : 34962 "; - fout << " },\n"; - // vnorm - fout << " { "; - fout << "\"buffer\" : " << 3+vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - fout << "\"byteLength\" : " << this->vm[vmi]->vnorm_bytes() << ", "; - fout << "\"target\" : 34962 "; - fout << " }"; - fout << (vmi < this->vm.size()-1 ? ",\n" : "\n"); - } - fout << " ],\n"; - - fout << " \"accessors\" : [\n"; - for (std::size_t vmi = 0u; vmi < this->vm.size(); ++vmi) { - this->vm[vmi]->computeVertexMaxMins(); - // indices - fout << " { "; - fout << "\"bufferView\" : " << vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - // 5123 unsigned short, 5121 unsigned byte, 5125 unsigned int, 5126 float: - fout << "\"componentType\" : 5125, "; - fout << "\"type\" : \"SCALAR\", "; - fout << "\"count\" : " << this->vm[vmi]->indices_size(); - fout << "},\n"; - // vpos - fout << " { "; - fout << "\"bufferView\" : " << 1+vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - fout << "\"componentType\" : 5126, "; - fout << "\"type\" : \"VEC3\", "; - fout << "\"count\" : " << this->vm[vmi]->vpos_size()/3; - // vertex position requires max/min to be specified in the gltf format - fout << ", \"max\" : " << this->vm[vmi]->vpos_max() << ", "; - fout << "\"min\" : " << this->vm[vmi]->vpos_min(); - fout << " },\n"; - // vcol - fout << " { "; - fout << "\"bufferView\" : " << 2+vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - fout << "\"componentType\" : 5126, "; - fout << "\"type\" : \"VEC3\", "; - fout << "\"count\" : " << this->vm[vmi]->vcol_size()/3; - fout << "},\n"; - // vnorm - fout << " { "; - fout << "\"bufferView\" : " << 3+vmi*4 << ", "; - fout << "\"byteOffset\" : 0, "; - fout << "\"componentType\" : 5126, "; - fout << "\"type\" : \"VEC3\", "; - fout << "\"count\" : " << this->vm[vmi]->vnorm_size()/3; - fout << "}"; - fout << (vmi < this->vm.size()-1 ? ",\n" : "\n"); - } - fout << " ],\n"; - - // Default material is single sided, so make it double sided - fout << " \"materials\" : [ { \"doubleSided\" : true } ],\n"; - - fout << " \"asset\" : {\n" - << " \"generator\" : \"https://github.com/sebsjames/mathplot: mplot::Visual::savegltf() (ver " - << mplot::version_string() << ")\",\n" - << " \"version\" : \"2.0\"\n" // This version is the *glTF* version. - << " }\n"; - fout << "}\n"; - fout.close(); - } - - void set_winsize (const std::int32_t _w, const std::int32_t _h) { this->window_w = _w; this->window_h = _h; } - - // Accessing std::vector>> vm; from external code - std::vector>>::const_iterator next_vm_accessor; - void init_vm_accessor() { this->next_vm_accessor = this->vm.begin(); } - mplot::VisualModel* get_next_vm_accessor() - { - mplot::VisualModel* cvm = nullptr; - if (this->next_vm_accessor != this->vm.end()) { - cvm = (*this->next_vm_accessor).get(); - this->next_vm_accessor++; - } - return cvm; - } - - std::uint32_t get_id() const { return this->visual_id; } - - protected: - - //! Set up a perspective projection based on window width and height. Not public. - void setPerspective() - { - // Calculate aspect ratio - float aspect = static_cast(this->window_w) / static_cast(this->window_h ? this->window_h : 1); - // Set perspective projection - this->projection = sm::mat::perspective (this->fov, aspect, this->zNear, this->zFar); - // Compute the inverse projection matrix - this->invproj = this->projection.inverse(); - } - - /*! - * Set an orthographic projection. This is not a public function. To choose orthographic - * projection for your Visual, write something like: - * - * \code - * mplot::Visual<> v(width, height, title); - * v.ptype = mplot::perspective_type::orthographic; - * \endcode - */ - void setOrthographic() - { - this->projection = sm::mat::orthographic (this->ortho_lb, this->ortho_rt, this->zNear, this->zFar); - this->invproj = this->projection.inverse(); - } - - // Rotate about the point this->rotation_centre. Subroutine for computeSceneview. - void computeSceneview_about_rotation_centre() - { - sm::mat sv_tr = sm::mat::identity(); - sm::mat sv_rot = sm::mat::identity(); - sv_tr.translate (this->scenetrans_delta); - // A rotation delta in world frame about the 'screen centre' - sv_rot.translate (this->rotation_centre); - sv_rot.rotate (this->rotation_delta); - sv_rot.translate (-this->rotation_centre); - - this->sceneview = sv_tr * sv_rot * this->savedSceneview; - this->sceneview_tr = sv_tr * this->savedSceneview_tr; - } - - // Get a camera movement that moves us nearer to target. - template - sm::vec get_cam_movement (sm::mat& current, const sm::mat& target, - sm::vec& vel, const T tc) const - { - const sm::vec delta = target.translation() - current.translation(); - const sm::vec force = delta - (vel * T{2}); - sm::vec pos_shift = vel * tc; - vel += force * tc; - return pos_shift; - } - - template - sm::quaternion get_cam_rotation (const sm::quaternion& r_cur0, const sm::mat& target, - T& rvel, const T tc) const - { - sm::mat target0 = target; - target0.translate (-target.translation()); - sm::quaternion r_targ0 = target0.rotation(); - r_targ0.renormalize(); - - sm::quaternion r_sz = r_targ0 * r_cur0.inverse(); - sm::vec aa = r_sz.axis_angle(); - T delta = aa[3]; // The angle subtended by the rotation - T force = delta - (rvel * T{2}); - // rvel is radpersec delta/tc - T prop = rvel * tc; - rvel += force * tc; - if (r_cur0.checkunit() == false) { throw std::runtime_error ("r_cur0 is not a unit quaternion (could renormalize here)"); } - sm::quaternion newpos = r_cur0.slerp (r_targ0, prop); - return newpos; // rather than prop, as in get_cam_movement - } - - void switch_view_follows_mode() - { - // Relevant only if there is a followedVM - if (this->followedVM == nullptr) { return; } - - if (this->options.test (visual_options::viewFollowsVMBehind) == true - && this->options.test (visual_options::viewFollowsVMTranslations) == false) { - this->options.reset (visual_options::viewFollowsVMBehind); - this->options.set (visual_options::viewFollowsVMTranslations); - this->state.set (visual_state::viewFollowsModeChanged); - std::cout << "sceneview follows agent movements (overview)\n"; - } else { // this->options.test (mplot::visual_options::viewFollowsVMTranslations) == true - this->options.set (visual_options::viewFollowsVMBehind); - this->state.set (visual_state::viewFollowsModeChanged); - this->options.reset (visual_options::viewFollowsVMTranslations); - std::cout << "sceneview follows behind agent (follower view)\n"; - } - } - - // Compile-time function to create a rotate-about-y transform - static constexpr sm::mat rotate_about_y() - { - sm::mat r = sm::mat::identity(); - r.rotate (sm::vec<>::uy(), sm::mathconst::pi); - return r; - } - - // Hold an offset translation and rotation for the follow-me camera - static constexpr sm::vec folcam_offset_tr_default = {0, 0.01f, -0.06f}; - sm::vec folcam_offset_tr = folcam_offset_tr_default; - sm::quaternion folcam_offset_rot; - - sm::mat update_viewmatrix_towards_target (const sm::mat& target) - { - sm::mat fol_cur = sm::mat::identity(); - - // Compute folcam_viewmatrix from sceneview (it's the inverse, along with a rotation) - constexpr sm::mat rotn_y = rotate_about_y(); - sm::mat folcam_viewmatrix = this->sceneview.inverse() * rotn_y; - - const sm::vec folcam_vm_trans = folcam_viewmatrix.translation(); - - fol_cur.translate (folcam_vm_trans); // encode just the location of the following camera - - // The current rotation of the scene view - folcam_viewmatrix.translate (-folcam_vm_trans); - sm::quaternion r_cur0 = folcam_viewmatrix.rotation(); - r_cur0.renormalize(); - - // get_cam_movement computes the positional shift - sm::vec pos_shift = this->get_cam_movement (fol_cur, target, this->followedVM_vel, this->trans_tc); - // get_cam_rotation computes the rotation for the next camera position - sm::quaternion cam_rotn = this->get_cam_rotation (r_cur0, target, this->followedVM_rvel, this->rotn_tc); - - // set the translation/rotation into fol_cur - fol_cur.pretranslate (pos_shift); - fol_cur.rotate (cam_rotn); - - // Distance to rotation centre should be the distance to the followedVM - this->d_to_rotation_centre = folcam_offset_tr.length(); - - // fol_cur now contains the new position and orientation for the following camera - return fol_cur; - } - - // To zoom down to, and follow behind the agent - sm::mat update_folcam_viewmatrix() - { - if (this->followedVM == nullptr) { return sm::mat::identity(); } - // Target view from the followedVM - sm::mat rmat = sm::mat::identity(); - rmat.rotate (this->folcam_offset_rot); - // To smooth this, I need to keep a time-average of followedVM->getViewMatrix()... - sm::mat fol_targ = this->followedVM->getViewMatrix() * rmat; - fol_targ.translate (this->folcam_offset_tr); - // FIXME: I may want to update the lastSceneview matrix as fol_targ moves. - return update_viewmatrix_towards_target (fol_targ); - } - - // To zoom back to the drone view - sm::mat update_overcam_viewmatrix() - { - if (this->followedVM == nullptr) { return sm::mat::identity(); } - // fol_targ will be the inverse of the lastSceneview - constexpr sm::mat rotn_y = rotate_about_y(); - sm::mat targ = this->lastSceneview.inverse() * rotn_y; - return update_viewmatrix_towards_target (targ); - } - - // A follow-me camera view - void computeSceneview_for_follower() - { - sm::mat folcam_viewmatrix = this->update_folcam_viewmatrix(); - constexpr sm::mat rotn_y = rotate_about_y(); - this->sceneview = rotn_y * folcam_viewmatrix.inverse(); - this->savedSceneview = this->sceneview; - } - - // When we're not close to the 'overview cam' location (which is the last place you were - // before you went into viewFollowsVMBehind mode) then we need this function to get there - void computeSceneview_for_overcam() - { - sm::mat overcam_viewmatrix = this->update_overcam_viewmatrix(); // target is lastSceneview - constexpr sm::mat rotn_y = rotate_about_y(); - this->sceneview = rotn_y * overcam_viewmatrix.inverse(); - this->savedSceneview = this->sceneview; - } - - /* - * For the time t, compute the location x of a 1D minimum-jerk trajectory from 0 to xf - * carried out in time tf. - */ - template - F compute_min_jerk (const F tf, const F xf, const F t) const noexcept - { - sm::mat A = { - std::pow (tf, F{3}), F{3} * std::pow (tf, F{2}), F{6} * tf, - std::pow (tf, F{4}), F{4} * std::pow (tf, F{3}), F{2} * std::pow (tf, F{2}), - std::pow (tf, F{5}), F{5} * std::pow (tf, F{4}), F{20} * std::pow (tf, F{3}) - }; - sm::vec B = { xf, F{0}, F{0} }; - sm::vec X = A.inverse() * B; // X are the min. jerk coefficients - - F x = X[0] * t * t * t + X[1] * std::pow (t, F{4}) + X[2] * std::pow (t, F{5}); - return x; - } - - // Helper function. Is the automatic sceneview change complete after since_frames? - bool autoSceneviewComplete (const std::uint32_t since_frames) - { - return (since_frames > this->currentAutoSceneviewChange.transform_time_frames); - } - - // Choreographed sceneview changes (direction_event) - void computeSceneview_for_automation() - { - // A constexpr rotation matrix, used below - constexpr sm::mat rotn_y = rotate_about_y(); - - // We're in an 'automation mode'. use this->currentAutoSceneviewChange - std::uint32_t since_frames = this->render_counter - this->currentAutoSceneviewChange.start_frame; - - // Determine how far, in time, as a proportion, we are into the automated sceneview movement - float propn = static_cast(since_frames) / static_cast(this->currentAutoSceneviewChange.transform_time_frames); - - if (this->currentAutoSceneviewChange.event == direction_event::timed_translation) { - - if (this->autoSceneviewComplete (since_frames)) { - // Completed movement time - this->scenetrans_delta = this->currentAutoSceneviewChange.translation; - this->computeSceneview_about_rotation_centre(); - this->state.set (visual_state::viewAutomation, false); - this->scenetrans_delta.zero(); - this->savedSceneview = this->sceneview; - this->savedSceneview_tr = this->sceneview_tr; - if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } - } else { - // Translate by an increment - if (this->currentAutoSceneviewChange.min_jerk) { - propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, - static_cast(since_frames)); - } - - this->scenetrans_delta = propn * this->currentAutoSceneviewChange.translation; - this->computeSceneview_about_rotation_centre(); - } - if (this->followedVM != nullptr) { - sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; - sm::mat fvm = this->followedVM->getViewMatrix(); - this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); - } - - } else if (this->currentAutoSceneviewChange.event == direction_event::timed_rotation) { - - sm::vec mod_up = this->savedSceneview.rotation() * this->scene_up; - if (this->autoSceneviewComplete (since_frames)) { - // Apply full rotation - sm::quaternion r1 (mod_up, -this->currentAutoSceneviewChange.about_vert_angle); - sm::quaternion r2 (this->scene_right, -this->currentAutoSceneviewChange.tilt_angle); - this->rotation_delta = r2 * r1; - this->computeSceneview_about_rotation_centre(); - this->state.set (visual_state::viewAutomation, false); - this->rotation_delta.reset(); - this->savedSceneview = this->sceneview; - this->savedSceneview_tr = this->sceneview_tr; - if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } - } else { // Rotate by an increment - if (this->currentAutoSceneviewChange.min_jerk) { - propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, - static_cast(since_frames)); - } - // make rotation_delta from this->currentAutoSceneviewChange.rotation and apply - sm::quaternion r1 (mod_up, -propn * this->currentAutoSceneviewChange.about_vert_angle); - sm::quaternion r2 (this->scene_right, -propn * this->currentAutoSceneviewChange.tilt_angle); - this->rotation_delta = r2 * r1; - this->computeSceneview_about_rotation_centre(); - } - if (this->followedVM != nullptr) { - sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; - sm::mat fvm = this->followedVM->getViewMatrix(); - this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); - } - - } else if (this->currentAutoSceneviewChange.event == direction_event::timed_transform - || this->currentAutoSceneviewChange.event == direction_event::sceneview) { // translation and rotation - - if (this->autoSceneviewComplete (since_frames)) { // transform is done - this->state.set (visual_state::viewAutomation, false); - this->scenetrans_delta.zero(); - this->rotation_delta.reset(); - this->savedSceneview = this->sceneview; - this->savedSceneview_tr = this->sceneview_tr; - // Update followedLastViewMatrix now! - if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } - } else { // transform, incrementally - if (this->currentAutoSceneviewChange.min_jerk) { - // propn is time from 0 to 1 of our movement. Compute min-jerk movement x(t) - // = a3 t^3 + a4 t^4 + a5 t^5. We always pass xf = 1, as we are getting a - // proportion of the trajectory, regardless of the length (or amount of - // rotation) of our sceneview move.) - propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, - static_cast(since_frames)); - } - // Ensure propn is in range before calling slerp - if (propn > 1.0f) { propn = 1.0f; } - if (propn < 0.0f) { propn = 0.0f; } - // Translate by an increment - this->scenetrans_delta = propn * this->currentAutoSceneviewChange.translation; - // Rotate... - sm::quaternion slerped = this->currentAutoSceneviewChange.rotation_start.slerp (currentAutoSceneviewChange.rotation, propn); - { - // Here's how to check the error information in the returned quaternion. - if (slerped.w == std::numeric_limits::max()) { std::cout << __func__ << ": propn = " << propn << " was out of the range [0, 1]\n"; } - if (slerped.x == std::numeric_limits::max()) { std::cout << __func__ << ": rotation_start was not normalized\n"; } - if (slerped.y == std::numeric_limits::max()) { std::cout << __func__ << ": rotation was not normalized\n"; } - - // rather than computeSceneview_about_rotation_centre, we compute - // translation and rotation right here (this could probably be consolidated to use fewer mats) - sm::mat sv_tr = sm::mat::identity(); - sm::mat sv_rot = sm::mat::identity(); - sv_tr.translate (this->savedSceneview.translation()); - sv_tr.translate (this->scenetrans_delta); - sv_rot.rotate (slerped); - this->sceneview = sv_tr * sv_rot; - this->sceneview_tr = sv_tr; - } - } - if (this->followedVM != nullptr) { - sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; - sm::mat fvm = this->followedVM->getViewMatrix(); - this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); - } else { - this->d_to_rotation_centre = std::abs (this->sceneview[14]); - } - - } else if (this->currentAutoSceneviewChange.event == direction_event::timed_orbit) { - if (this->autoSceneviewComplete (since_frames)) { // transform is done - this->state.set (visual_state::viewAutomation, false); - this->scenetrans_delta.zero(); - this->rotation_delta.reset(); - this->savedSceneview = this->sceneview; - this->savedSceneview_tr = this->sceneview_tr; - // Update followedLastViewMatrix now! - if (this->followedVM != nullptr) { this->followedLastViewMatrix = this->followedVM->getViewMatrix(); } - } else { // orbit, incrementally - if (this->currentAutoSceneviewChange.min_jerk) { - propn = this->compute_min_jerk (static_cast(this->currentAutoSceneviewChange.transform_time_frames), 1.0f, - static_cast(since_frames)); - } - sm::mat orb_trans = sm::mat::identity(); - orb_trans.translate (this->currentAutoSceneviewChange.orbit_centre); - sm::mat orb_trans_back = sm::mat::identity(); - orb_trans_back.translate (-this->currentAutoSceneviewChange.orbit_centre); - sm::mat orb_rot = sm::mat::identity(); - orb_rot.rotate (this->currentAutoSceneviewChange.orbit_axis, propn * this->currentAutoSceneviewChange.orbit_angle); - this->sceneview = this->savedSceneview * orb_trans * orb_rot * orb_trans_back; - } - } else { - std::cout << "Unknown direction_event\n"; - this->state.set (visual_state::viewAutomation, false); - } - } - - // This is called every time render() is called - void computeSceneview() - { - if (this->options.test (visual_options::viewFollowsVMBehind) && this->followedVM != nullptr) { - - if (this->state.test (visual_state::viewFollowsModeChanged)) { - // Record sceneview now - this->lastSceneview = this->sceneview; - this->lastSceneview_tr = this->sceneview_tr; - // THEN, we can update lastSceneview whilst also updating agent location - // then zoom back to lastSceneview as the target. - this->state.reset (visual_state::viewFollowsModeChanged); - } - - // Use scenetrans_delta to shift the view with the scrollwheel - this->folcam_offset_tr += this->scenetrans_delta; - this->scenetrans_delta.zero(); - if (this->state.test (visual_state::scrolling)) { - this->state.reset (visual_state::scrolling); - // scrolling during a view automation should cancel the view automation - this->state.reset (visual_state::viewAutomation); - } - this->computeSceneview_for_follower(); - - } else { - - // A constexpr rotation matrix, used below - constexpr sm::mat rotn_y = rotate_about_y(); - - if (this->state.test (visual_state::viewFollowsModeChanged)) { - // Changed back to normal, non-follower mode. Zoom back, so set viewTransition - this->state.set (visual_state::viewTransition); - this->state.reset (visual_state::viewFollowsModeChanged); - } - - // if sceneview is not close to lastSceneview and we have no commanded rotations - // (scenetrans_delta and rotation_delta are 0) then we make changes to return to - // lastSceneview: - if (this->state.test (visual_state::viewTransition) - && this->followedVM != nullptr - && std::abs(this->scenetrans_delta.sum()) == 0.0f - && this->rotation_delta.is_zero_rotation() == true) { - - // zoom towards lastSceneview: - this->computeSceneview_for_overcam(); - // Update d_to_rotation_centre with distance to followedVM - // scene view in world frame - sm::mat sv_viewmatrix = this->sceneview.inverse() * rotn_y; - // followed vm - sm::mat fvm = this->followedVM->getViewMatrix(); - - this->d_to_rotation_centre = (fvm.translation() - sv_viewmatrix.translation()).length(); - - // Did we get there? If so, set viewTransition false - if ((this->sceneview.translation() - this->lastSceneview.translation()).length() < 0.001f) { - this->state.reset (visual_state::viewTransition); - } - } else if (this->state.test (visual_state::viewAutomation)) { - - this->computeSceneview_for_automation(); - - } else { - - if (std::abs(this->scenetrans_delta.sum()) > 0.0f || this->rotation_delta.is_zero_rotation() == false) { - // Calculate model view transformation - transforming from "model space" to "worldspace". - this->computeSceneview_about_rotation_centre(); - // As we had a commanded movement, cancel the viewTransition and any viewAutomation - this->state.reset (visual_state::viewTransition); - this->state.reset (visual_state::viewAutomation); - } // else don't change sceneview - - if (this->state.test (visual_state::scrolling)) { - this->scenetrans_delta.zero(); - this->state.reset (visual_state::scrolling); - } - } - - if (this->options.test (visual_options::viewFollowsVMTranslations) - && this->followedVM != nullptr - && this->state.test (visual_state::viewAutomation) == false - && this->followedLastViewMatrix != this->followedVM->getViewMatrix()) { - - // Move camera the difference between followedLastViewMatrix and - // followedVM->getViewMatrix() in the screen frame of reference. - sm::vec fol_screenframe = (this->sceneview * followedLastViewMatrix.translation() - - this->sceneview * followedVM->getViewMatrix().translation()).less_one_dim(); - - this->sceneview.pretranslate (fol_screenframe); - this->sceneview_tr.pretranslate (fol_screenframe); - this->savedSceneview.pretranslate (fol_screenframe); - this->savedSceneview_tr.pretranslate (fol_screenframe); - this->lastSceneview.pretranslate (fol_screenframe); - this->lastSceneview_tr.pretranslate (fol_screenframe); - - this->followedLastViewMatrix = this->followedVM->getViewMatrix(); - } - } - } - - //! A vector of pointers to all the mplot::VisualModels (HexGridVisual, - //! ScatterVisual, etc) which are going to be rendered in the scene. - std::vector>> vm; - - //! If the view should follow a model (options viewFollowsVMTranslations and ...Rotations), this is the one. - mplot::VisualModel* followedVM = nullptr; - - //! Holds the current velocy of the followedVM follower - sm::vec followedVM_vel = {}; - //! Current rotational speed (how fast we slerp) - float followedVM_rvel = 0.0f; - - //! Holds the viewmatrix of the followedVM the last time we called render - sm::mat followedLastViewMatrix = sm::mat::identity(); - - //! The window (and OpenGL context) for this Visual - mplot::win_t* window = nullptr; - - //! Each window has an ID number, which is passed to the owned VisualModels - std::uint32_t visual_id = std::numeric_limits::max(); - - //! Current window width - std::int32_t window_w = 640; - //! Current window height - std::int32_t window_h = 480; - //! Window viewport scaling - float window_scale_w = 1.0f; - float window_scale_h = 1.0f; - - //! The title for the Visual. Used in window title and if saving out 3D model or png image. - std::string title = "mathplot"; - - //! The user's 'selected visual model'. For model specific changes to alpha and possibly colour - std::uint32_t selectedVisualModel = 0u; - - //! A little model of the coordinate axes. - std::unique_ptr> coordArrows; - - //! Position coordinate arrows on screen. Configurable at mplot::Visual construction. - sm::vec coordArrowsOffset = { -0.8f, -0.8f }; - - /* - * Variables to manage projection and rotation of the scene - */ - - //! Current cursor position - sm::vec cursorpos = {}; - - //! The default z position for VisualModels should be 'away from the screen' (negative) so we can see them! - constexpr static float zDefault = -5.0f; - - //! A delta scene translations - sm::vec scenetrans_delta = {}; - - //! Default for scene translation. This is a scene position that can be reverted to, to - //! 'reset the view'. This is copied into sceneview when user presses Ctrl-a. - sm::vec scenetrans_default = { 0.0f, 0.0f, zDefault }; - - //! The world depth at which text objects should be rendered - float text_z = -1.0f; - - //! Screen coordinates of the position of the last mouse press - sm::vec mousePressPosition = {}; - - //! Add additional rotation to the scene - sm::quaternion rotation_delta; - - //! The default rotation of the scene, to reconstruct the default sceneview matrix/reset rotation. - sm::quaternion rotation_default; - - //! A coordinate in the scene about which to perform a mouse-driven rotation. May be set to - //! the centre of the closest VisualModel object. - sm::vec rotation_centre = {}; - - // Distance to the 'rotation centre'. Used to scale the effect of the scroll wheel - float d_to_rotation_centre = -zDefault; - - //! The projection matrix is a member of this class. Value is set during setPerspective() or setOrthographic() - sm::mat projection = sm::mat::identity(); - - //! The inverse of the projection. Value is set during setPerspective() or setOrthographic() - sm::mat invproj = sm::mat::identity(); - - //! The sceneview matrix, which changes as the user moves the view with mouse - //! movements. Initialized in VisualOwnable constructor. - sm::mat sceneview = sm::mat::identity(); - //! The non-rotating sceneview matrix, updated only from mouse translations (avoiding rotations) - sm::mat sceneview_tr = sm::mat::identity(); - - //! Saved sceneview at mouse button down - sm::mat savedSceneview = sm::mat::identity(); - //! Saved sceneview_tr - sm::mat savedSceneview_tr = sm::mat::identity(); - - //! The sceneview when the user switched to a follow-me mode. This can become a target to return to when switching back. - sm::mat lastSceneview = sm::mat::identity(); - //! translation only version of lastSceneview - sm::mat lastSceneview_tr = sm::mat::identity(); - - // auto sceneview change. Active if visual_state::viewAutomation is set true in this->state. - mplot::direction_data currentAutoSceneviewChange; - - public: - - //! Getter for d_to_rotation_centre - float get_d_to_rotation_centre() const { return this->d_to_rotation_centre; } - - /* - * Generic callback handlers - */ - - using keyaction = mplot::keyaction; - using keymod = mplot::keymod; - using key = mplot::key; - // The key_callback handler uses GLFW codes, but they're in a mplot header (keys.h) - template - bool key_callback (std::int32_t _key, std::int32_t scancode, std::int32_t action, std::int32_t mods) // can't be virtual. - { - bool needs_render = false; - - if constexpr (owned == true) { // If Visual is 'owned' then the owning system deals with program exit - // Exit action - if (_key == key::q && (mods & keymod::control) && action == keyaction::press) { - this->signal_to_quit(); - } - } - - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::c && (mods & keymod::control) && action == keyaction::press) { - this->options.flip (visual_options::showCoordArrows); - needs_render = true; - } - - if (_key == key::h && (mods & keymod::control) && action == keyaction::press) { - // Help to stdout: - std::cout << "Ctrl-h: Output this help to stdout\n" - << "Mouse-primary: rotate mode (use Ctrl to change axis)\n" - << "Mouse-secondary: translate mode\n"; - if constexpr (owned == true) { // If Visual is 'owned' then the owning system deals with program exit - std::cout << "Ctrl-q: Request exit\n"; - } - std::cout << "Ctrl-v: Un-pause\n" - << "Ctrl-l: Toggle the scene lock\n" - << "Ctrl-c: Toggle coordinate arrows\n" - << "Ctrl-s: Take a snapshot\n" - << "Ctrl-Shift-s: Output GLSL shaders to stdout\n" - << "Ctrl-m: Save 3D models in .gltf format (open in e.g. blender)\n" - << "Ctrl-a: Reset default view\n" - << "Ctrl-o: Reduce field of view\n" - << "Ctrl-p: Increase field of view\n" - << "Ctrl-7: Decrease ambient light intensity\n" - << "Ctrl-8: Increase ambient light intensity\n" - << "Ctrl-9: Decrease diffuse light intensity\n" - << "Ctrl-0: Increase diffuse light intensity\n" - << "Ctrl-e: Sceneview matrix to stdout\n" - << "Ctrl-y: Cycle perspective\n" - << "Ctrl-k: Toggle rotate about central model or scene origin\n" - << "Ctrl-b: Toggle between 'rotate about vertical', or 'mathplot tilt'\n" - << "Ctrl-d: Switch the vertical axis used in 'rotate about vertical' mode\n" - << "Ctrl-z: Show the current scenetrans/rotation on stdout\n" - << "Ctrl-u: Reduce zNear cutoff plane\n" - << "Ctrl-i: Increase zNear cutoff plane\n" - << "Ctrl-j: Toggle bounding boxes\n" - << "Ctrl-Shift-s: Output shaders to stdout\n" - << "F1-F10: Select model index (with shift: toggle hide)\n" - << "Shift-Left: Decrease opacity of selected model\n" - << "Shift-Right: Increase opacity of selected model\n" - << std::flush; - } - - if (_key == key::l && (mods & keymod::control) && action == keyaction::press) { - this->state.flip (visual_state::sceneLocked); - std::cout << "Scene is now " << (this->state.test (visual_state::sceneLocked) ? "" : "un-") << "locked\n"; - } - - if (_key == key::e && (mods & keymod::control) && action == keyaction::press) { - constexpr sm::mat rotn_y = rotate_about_y(); - sm::mat effective_viewmatrix = this->sceneview.inverse() * rotn_y; - std::cout << this->title << " window:\n Sceneview effective camera location is " << (effective_viewmatrix * sm::vec<>{}) << std::endl; - std::cout << " Sceneview matrix array:\n" << this->sceneview.str_arr() << std::endl; - } - - if (_key == key::v && (mods & keymod::control) && action == keyaction::press) { - if (this->state.test (visual_state::paused)) { - this->state.set (visual_state::paused, false); - std::cout << "Scene un-paused\n"; - } // else no-op - } - - if (_key == key::s && (mods & (keymod::control | keymod::shift)) && action == keyaction::press) { - - if ((mods & (keymod::control | keymod::shift)) == (keymod::control | keymod::shift)) { - // Ctrl-Shift-s gives you the default shaders - std::cout << "The built-in shader programs are:\n"; - std::cout << "\nVisual.vert.glsl\n" - << "----------------\n" - << mplot::getDefaultVtxShader(glver) << std::endl; - std::cout << "\nVisual.frag.glsl\n" - << "----------------\n" - << mplot::getDefaultFragShader(glver) << std::endl; - std::cout << "\nVisText.vert.glsl\n" - << "----------------\n" - << mplot::getDefaultTextVtxShader(glver) << std::endl; - std::cout << "\nVisText.frag.glsl\n" - << "----------------\n" - << mplot::getDefaultTextFragShader(glver) << std::endl; - } else if (mods & keymod::control) { - // Ctrl-s saves a PNG - std::string fname (this->title); - mplot::tools::stripFileSuffix (fname); - fname += ".png"; - // Make fname 'filename safe' - mplot::tools::conditionAsFilename (fname); - this->saveImage (fname); - std::cout << "Saved image to '" << fname << "'\n"; - } - } - - // Save gltf 3D file - if (_key == key::m && (mods & keymod::control) && action == keyaction::press) { - std::string gltffile = this->title; - mplot::tools::stripFileSuffix (gltffile); - gltffile += ".gltf"; - mplot::tools::conditionAsFilename (gltffile); - this->savegltf (gltffile); - std::cout << "Saved 3D file '" << gltffile << "'\n"; - } - - if (_key == key::z && (mods & keymod::control) && action == keyaction::press) { - sm::quaternion rotn = this->sceneview.rotation(); - rotn.renormalize(); - sm::vec scenetrans = this->sceneview.translation(); - std::cout << "Scenetrans setup code:\n v.setSceneTrans (sm::vec{ float{" - << scenetrans.x() << "}, float{" - << scenetrans.y() << "}, float{" - << scenetrans.z() - << "} });" - << "\n v.setSceneRotation (sm::quaternion{ float{" - << rotn.w << "}, float{" << rotn.x << "}, float{" - << rotn.y << "}, float{" << rotn.z << "} });\n"; - } - - // Set selected model - if (_key == key::f1 && action == keyaction::press) { - this->selectedVisualModel = 0; - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f2 && action == keyaction::press) { - if (this->vm.size() > 1) { this->selectedVisualModel = 1; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f3 && action == keyaction::press) { - if (this->vm.size() > 2) { this->selectedVisualModel = 2; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f4 && action == keyaction::press) { - if (this->vm.size() > 3) { this->selectedVisualModel = 3; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f5 && action == keyaction::press) { - if (this->vm.size() > 4) { this->selectedVisualModel = 4; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f6 && action == keyaction::press) { - if (this->vm.size() > 5) { this->selectedVisualModel = 5; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f7 && action == keyaction::press) { - if (this->vm.size() > 6) { this->selectedVisualModel = 6; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f8 && action == keyaction::press) { - if (this->vm.size() > 7) { this->selectedVisualModel = 7; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f9 && action == keyaction::press) { - if (this->vm.size() > 8) { this->selectedVisualModel = 8; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } else if (_key == key::f10 && action == keyaction::press) { - if (this->vm.size() > 9) { this->selectedVisualModel = 9; } - std::cout << "Selected visual model index " << this->selectedVisualModel << std::endl; - } - - // Toggle hide model if the shift key is down - if ((_key == key::f10 || _key == key::f1 || _key == key::f2 || _key == key::f3 - || _key == key::f4 || _key == key::f5 || _key == key::f6 - || _key == key::f7 || _key == key::f8 || _key == key::f9) - && action == keyaction::press && (mods & keymod::shift)) { - this->vm[this->selectedVisualModel]->toggleHide(); - } - - // Increment/decrement alpha for selected model - if (_key == key::left && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::shift)) { - if (!this->vm.empty()) { this->vm[this->selectedVisualModel]->decAlpha(); } - } - if (_key == key::right && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::shift)) { - if (!this->vm.empty()) { this->vm[this->selectedVisualModel]->incAlpha(); } - } - - // Ambient and diffuse lighting intensity - if (_key == key::n9 && action == keyaction::press && (mods & keymod::control)) { - // decrease diffuse intensity - this->diffuse_intensity -= 0.05f; - if (this->diffuse_intensity <= 0.0f) { this->diffuse_intensity = 0.0f; } - std::cout << "diffuse_intensity is now " << this->diffuse_intensity << std::endl; - } else if (_key == key::n0 && action == keyaction::press && (mods & keymod::control)) { - // increase diffuse intensity - this->diffuse_intensity += 0.05f; - if (this->diffuse_intensity > 10.0f) { this->diffuse_intensity = 10.0f; } - std::cout << "diffuse_intensity is now " << this->diffuse_intensity << std::endl; - } else if (_key == key::n7 && action == keyaction::press && (mods & keymod::control)) { - // decrease ambient intensity - this->ambient_intensity -= 0.05f; - if (this->ambient_intensity <= 0.0f) { this->ambient_intensity = 0.0f; } - std::cout << "ambient_intensity is now " << this->ambient_intensity << std::endl; - } else if (_key == key::n8 && action == keyaction::press && (mods & keymod::control)) { - // increase ambient intensity - this->ambient_intensity += 0.05f; - if (this->ambient_intensity > 10.0f) { this->ambient_intensity = 10.0f; } - std::cout << "ambient_intensity is now " << this->ambient_intensity << std::endl; - } - - // Reset view to default - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::a && (mods & keymod::control) && action == keyaction::press) { - std::cout << "Reset to default view\n"; - this->sceneview.set_identity(); - this->sceneview_tr.set_identity(); - this->sceneview.translate (this->scenetrans_default); - this->sceneview.rotate (this->rotation_default); - this->sceneview_tr.translate (this->scenetrans_default); - this->scenetrans_delta.zero(); - this->rotation_delta.reset(); - this->d_to_rotation_centre = -this->scenetrans_default[2]; - //this->folcam_offset = folcam_default(); - this->folcam_offset_tr = folcam_offset_tr_default; - this->folcam_offset_rot.reset(); - needs_render = true; - } - - if (_key == key::k && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::control)) { - this->options.flip (visual_options::rotateAboutSceneOrigin); - std::cout << "Rotating about " - << (this->options.test (visual_options::rotateAboutSceneOrigin) ? "scene origin" : "central model") - << std::endl; - } - - if (_key == key::j && (action == keyaction::press || action == keyaction::repeat) && (mods & keymod::control)) { - this->options.flip (visual_options::showBoundingBoxes); - // Update all the VisualModels now: - auto vmi = this->vm.begin(); - while (vmi != this->vm.end()) { - (*vmi)->show_bb (this->options.test (visual_options::showBoundingBoxes)); - ++vmi; - } - } - - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::o && (mods & keymod::control) && action == keyaction::press) { - this->fov -= 2.0f; - if (this->fov < 1.0f) { this->fov = 2.0f; } - std::cout << "FOV reduced to " << this->fov << std::endl; - } - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::p && (mods & keymod::control) && action == keyaction::press) { - this->fov += 2.0f; - if (this->fov > 179.0f) { this->fov = 178.0f; } - std::cout << "FOV increased to " << this->fov << std::endl; - } - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::u && (mods & keymod::control) && action == keyaction::press) { - this->zNear /= 2.0f; - std::cout << "zNear reduced to " << this->zNear << std::endl; - } - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::i && (mods & keymod::control) && action == keyaction::press) { - this->zNear *= 2.0f; - std::cout << "zNear increased to " << this->zNear << std::endl; - } - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::left_bracket && (mods & keymod::control) && action == keyaction::press) { - this->zFar /= 2.0f; - std::cout << "zFar reduced to " << this->zFar << std::endl; - } - if (this->state.test (visual_state::sceneLocked) == false - && _key == key::right_bracket && (mods & keymod::control) && action == keyaction::press) { - this->zFar *= 2.0f; - std::cout << "zFar increased to " << this->zFar << std::endl; - } - - if (_key == key::y && (mods & keymod::control) && action == keyaction::press) { - if (this->ptype == mplot::perspective_type::perspective) { - this->ptype = mplot::perspective_type::orthographic; - } else if (this->ptype == mplot::perspective_type::orthographic) { - this->ptype = mplot::perspective_type::perspective; - } - needs_render = true; - } - - if (_key == key::d && (mods & keymod::control) && action == keyaction::press) { - this->switch_scene_vertical_axis(); - } - - if (_key == key::b && (mods & keymod::control) && action == keyaction::press) { - this->options.flip (visual_options::rotateAboutVertical); - if (this->options.test (visual_options::rotateAboutVertical)) { - std::cout << "Mouse rotates scene about vertical axis\n"; - } else { - std::cout << "Mouse tilts scene as in the original mathplot\n"; - } - } - - this->key_callback_extra (_key, scancode, action, mods); - - return needs_render; - } - - // Switch between 'z' up and 'y' up - void switch_scene_vertical_axis() - { - if (this->scene_up == sm::vec<>::uy()) { - std::cout << "Changing 'scene up' to uz\n"; - this->scene_up = sm::vec<>::uz(); - this->scene_right = sm::vec<>::ux(); - this->scene_out = -sm::vec<>::uy(); - } else if (this->scene_up == sm::vec<>::uz()) { - std::cout << "Changing 'scene up' to uy\n"; - this->scene_up = sm::vec<>::uy(); - this->scene_right = sm::vec<>::ux(); - this->scene_out = sm::vec<>::uz(); - } else { - std::cout << "Not changing user-specified 'scene up' from " << this->scene_up << "\n"; - } - } - - //! Rotate the scene about axis by angle (angle in radians) - void rotate_scene (const sm::vec& axis, const float angle) - { - sm::quaternion rotnQuat (axis, -angle); - this->sceneview.rotate (rotnQuat); - } - - //! Find the rotation centre; either the scene origin or the centre of a perceptually nearby VM - void find_rotation_centre() - { - // When rotating about scene origin, find translation of scene centre from screen centre - if (this->options.test (visual_options::rotateAboutSceneOrigin) == true) { - this->rotation_centre = this->savedSceneview.translation(); - return; - } - - // Otherwise, find the centre of a visual model to rotate about - constexpr sm::vec v1 = { 0.0f, 0.0f, -100.0f }; - constexpr sm::vec v2 = { 0.0f, 0.0f, 100.0f }; - constexpr sm::vec v2v1 = v1 - v2; - - // A rotation delta in world frame about the 'screen centre'. This is a default: - if (this->rotation_centre == sm::vec{}) { - this->rotation_centre = { 0.0f, 0.0f, this->savedSceneview.translation().z() + this->scenetrans_delta.z() }; - } - - // There's an option to write out the bounding box corners to a file that can be - // displayed with debug_boundingboxes.cpp - std::ofstream fout; - std::uint32_t ci = 0; - if (options.test (visual_options::boundingBoxesToJson)) { - fout.open ("/tmp/mathplot_bounding_boxes.json", std::ios::out | std::ios::trunc); - if (fout.is_open()) { fout << "{\n"; } - } - - //std::multimap, mplot::VisualModel*> > possible_centres; // tuple: didn't work with g++ - std::multimap, mplot::VisualModel*> > possible_centres; // pair - auto vmi = this->vm.begin(); - while (vmi != this->vm.end()) { - - // vm_bools comes from VisualModel and would need to be shared - if ((*vmi)->flags.test (mplot::vm_bools::compute_bb) && !(*vmi)->flags.test (mplot::vm_bools::twodimensional)) { - - sm::vec tr_bb_centre = (this->savedSceneview * (*vmi)->get_viewmatrix_bb_centre()).less_one_dim(); - - if (options.test (visual_options::boundingBoxesToJson) && fout.is_open()) { - sm::interval> modelbb = (*vmi)->bb; // Get the VisualModel bounding box - modelbb -= (*vmi)->bb.mid(); // centre the bounding box about (VM frame's) origin - modelbb += tr_bb_centre; - fout << " \"b" << (ci + 1) << "\": [" << modelbb.min.str_comma_separated() << "],\n"; - fout << " \"b" << (ci + 2) << "\": [" << modelbb.max.str_comma_separated() << "],\n"; - ci += 2; - } - - // Highlight central VM in any case. Really, want to highlight the selected possible centre. - if (options.test (visual_options::highlightRotationVM)) { (*vmi)->show_bb (false); } - - // Find perpendicular distance from line to point pc - sm::vec cv = tr_bb_centre - v1; - float pdist = cv.length() * std::sin (v2v1.angle (cv)); - - if (tr_bb_centre[2] < 0.0f) { // Only if in front of viewer (z must be negative) - // Perp. distance as key, value is tuple of BB centre and visualmodel pointer - //possible_centres.insert ({ pdist, { tr_bb_centre, (*vmi).get() } }); // tuple - possible_centres.insert ({ pdist, std::make_pair (tr_bb_centre, (*vmi).get()) }); // pair - } - } - ++vmi; - } - - if (options.test (visual_options::boundingBoxesToJson) && fout.is_open()) { - fout << " \"n\": " << ci << "\n}\n"; - fout.close(); - } - - if (!possible_centres.empty()) { - //const auto [rcentre, vmptr] = possible_centres.begin()->second; // tuple - std::pair, mplot::VisualModel*> pr = possible_centres.begin()->second; // pair - // this->rotation_centre = rcentre; // tuple - this->rotation_centre = pr.first; // pair - this->d_to_rotation_centre = this->rotation_centre.length(); - //if (options.test (visual_options::highlightRotationVM)) { vmptr->show_bb (true); } // tuple - if (options.test (visual_options::highlightRotationVM)) { pr.second->show_bb (true); } // pair - } // else don't change rotation_centre - } - - virtual bool cursor_position_callback (double x, double y) - { - this->cursorpos[0] = static_cast(x); - this->cursorpos[1] = static_cast(y); - - sm::vec mouseMoveWorld = { 0.0f, 0.0f, 0.0f }; - - bool needs_render = false; - - // Mouse-movement gain - constexpr float mm_gain = 160.0f; - - // This is "rotate the scene" (and not "rotate one VisualModel") - if (this->state.test (visual_state::rotateMode)) { - // Convert mousepress/cursor positions (in pixels) to the range -1 -> 1: - sm::vec p0_coord = this->mousePressPosition; - p0_coord -= this->window_w * 0.5f; - p0_coord /= this->window_w * 0.5f; - sm::vec p1_coord = this->cursorpos; - p1_coord -= this->window_w * 0.5f; - p1_coord /= this->window_w * 0.5f; - // Note: don't update this->mousePressPosition until user releases button. - - // Add the depth at which the object lies. Use forward projection to determine the - // correct z coordinate for the inverse projection. This assumes only one object. - sm::vec point = { 0.0f, 0.0f, this->savedSceneview.translation().z(), 1.0f }; - sm::vec pp = this->projection * point; - float coord_z = pp[2] / pp[3]; // divide by pp[3] is divide by/normalise by 'w'. - - // p0_coord/p1_coord in range -1 to 1, with a z value of 1. - sm::vec p0 = { p0_coord[0], p0_coord[1], coord_z, 1.0f }; - sm::vec p1 = { p1_coord[0], p1_coord[1], coord_z, 1.0f }; - - // Apply the inverse projection to get two points in the world frame of reference - // for the mouse movement - sm::vec v0 = this->invproj * p0; - sm::vec v1 = this->invproj * p1; - - /* - * This computes the difference between v0 and v1, the 2 mouse positions in the - * world space. Note the swap between x and y. mouseMoveWorld is used as the - * rotation axis in the viewer's frame of reference or its values are used to set - * rotations about scene axes (if rotateAboutVertical is true) - */ - if (this->state.test (visual_state::rotateModMode)) { - // Sort of "rotate the page" mode. - mouseMoveWorld[2] = (-(v1[1] - v0[1]) + (v1[0] - v0[0])); - } else { - mouseMoveWorld[1] = -(v1[0] - v0[0]); - mouseMoveWorld[0] = -(v1[1] - v0[1]); - } - mouseMoveWorld *= mm_gain; - - if (this->options.test (visual_options::rotateAboutVertical) == true - && this->options.test (visual_options::viewFollowsVMBehind) == false) { - - if (this->state.test (visual_state::rotateModMode)) { - // What to do about rotate mod mode in this rotation scheme? Rotate about the missing axis for now. - this->rotation_delta.set_rotation (this->scene_out, mouseMoveWorld[2] * -sm::mathconst::deg2rad); - } else { - // For now, rotate about the scene up axis - sm::vec<> mod_up = this->savedSceneview.rotation() * this->scene_up; - sm::quaternion r1 (mod_up, mouseMoveWorld[1] * -sm::mathconst::deg2rad); - sm::quaternion r2 (this->scene_right, mouseMoveWorld[0] * -sm::mathconst::deg2rad); - this->rotation_delta = r2 * r1; - } - } else if (this->options.test (visual_options::viewFollowsVMBehind) == true) { - //std::cout << "\nmouseMoveWorld[0]: " << mouseMoveWorld[0] << std::endl; // pitch - //std::cout << "mouseMoveWorld[1]: " << mouseMoveWorld[1] << std::endl; // about +- 40ish. leftright yaw - float pitch = mouseMoveWorld[0]; - float yaw = mouseMoveWorld[1]; - pitch = pitch > 10.0f ? 10.0f : pitch; - pitch = pitch < -65.0f ? -65.0f : pitch; // negative pitch is 'looking down' on the agent - yaw = yaw > 45.0f ? 45.0f : yaw; - yaw = yaw < -45.0f ? -45.0f : yaw; - - sm::quaternion r1 (this->scene_up, yaw * sm::mathconst::deg2rad); - sm::quaternion r2 (this->scene_right, pitch * -sm::mathconst::deg2rad); - this->folcam_offset_rot = r2 * r1; - - } else { - // rotation_delta is the mouse-commanded rotation in the scene frame of reference - this->rotation_delta.set_rotation (mouseMoveWorld, mouseMoveWorld.length() * -sm::mathconst::deg2rad); - } - - needs_render = true; - - } else if (this->state.test (visual_state::translateMode)) { // allow only rotate OR translate for a single mouse movement - // Convert mousepress/cursor positions (in pixels) to the range -1 -> 1: - sm::vec p0_coord = this->mousePressPosition; - p0_coord -= this->window_w * 0.5f; - p0_coord /= this->window_w * 0.5f; - sm::vec p1_coord = this->cursorpos; - p1_coord -= this->window_w * 0.5f; - p1_coord /= this->window_w * 0.5f; - - this->mousePressPosition = this->cursorpos; - - // Add the depth at which the object lies. Use forward projection to determine the - // correct z coordinate for the inverse projection. This assumes only one object. - sm::vec point = { 0.0f, 0.0f, -this->d_to_rotation_centre, 1.0f }; - sm::vec pp = this->projection * point; - float coord_z = pp[2] / pp[3]; // divide by pp[3] is divide by/normalise by 'w'. - - // Construct two points for the start and end of the mouse movement - sm::vec p0 = { p0_coord[0], p0_coord[1], coord_z, 1.0f }; - sm::vec p1 = { p1_coord[0], p1_coord[1], coord_z, 1.0f }; - // Apply the inverse projection to get two points in the world frame of reference: - sm::vec v0 = this->invproj * p0; - sm::vec v1 = this->invproj * p1; - // This computes the difference betwen v0 and v1, the 2 mouse positions in the world - mouseMoveWorld[0] = (v1[0] / v1[3]) - (v0[0] / v0[3]); - mouseMoveWorld[1] = (v1[1] / v1[3]) - (v0[1] / v0[3]); - // Note: mouseMoveWorld[2] is unmodified - - // We "translate the whole scene" - used by 2D projection shaders - this->scenetrans_delta[0] += mouseMoveWorld[0]; - - if (this->options.test (visual_options::viewFollowsVMBehind) == true) { - this->scenetrans_delta[1] += mouseMoveWorld[1]; // opp. sense in follow-me - } else { - this->scenetrans_delta[1] -= mouseMoveWorld[1]; - } - - needs_render = true; // updates viewproj; uses this->scenetrans - } - - return needs_render; - } - - virtual void mouse_button_callback (std::int32_t button, std::int32_t action, std::int32_t mods = 0) - { - // If the scene is locked, then ignore the mouse movements - if (this->state.test (visual_state::sceneLocked)) { return; } - - // Record the position and rotation at which the button was pressed - if (action == keyaction::press) { // Button down - this->mousePressPosition = this->cursorpos; - this->savedSceneview = this->sceneview; - this->savedSceneview_tr = this->sceneview_tr; - this->scenetrans_delta.zero(); - this->rotation_delta.reset(); - } else if (action == keyaction::release) { - // On mouse button release, zero the deltas: - this->scenetrans_delta.zero(); - this->rotation_delta.reset(); - } - - this->find_rotation_centre(); - - if (button == mplot::mousebutton::left) { // Primary button means rotate - if (action == keyaction::press) { - this->state.set (visual_state::mouseButtonLeftPressed); - } else if (action == keyaction::release) { - this->state.set (visual_state::mouseButtonLeftPressed, false); - } - this->state.set (visual_state::rotateModMode, ((mods & keymod::control) ? true : false)); - this->state.set (visual_state::rotateMode, (action == keyaction::press)); - this->state.set (visual_state::translateMode, false); - } else if (button == mplot::mousebutton::right) { // Secondary button means translate - if (action == keyaction::press) { - this->state.set (visual_state::mouseButtonRightPressed); - } else if (action == keyaction::release) { - this->state.set (visual_state::mouseButtonRightPressed, false); - } - this->state.set (visual_state::rotateMode, false); - this->state.set (visual_state::translateMode, (action == keyaction::press)); - } - - this->mouse_button_callback_extra (button, action, mods); - } - - virtual bool window_size_callback (std::int32_t width, std::int32_t height) - { - this->window_w = width; - this->window_h = height; - return true; // needs_render - } - - virtual bool window_content_scale_callback (float xscl, float yscl) - { - bool nr = false; - if (this->window_scale_w != xscl) { - this->window_scale_w = xscl; - nr = true; - } - if (this->window_scale_h != yscl) { - this->window_scale_h = yscl; - nr = true; - } - return nr; - } - - virtual void window_close_callback() - { - if (this->options.test (visual_options::preventWindowCloseWithButton) == false) { - this->signal_to_quit(); - } else { - std::cerr << "Ignoring user request to exit (Visual::preventWindowCloseWithButton)\n"; - } - } - - //! When user scrolls, we translate the scene - virtual bool scroll_callback (double xoffset, double yoffset) - { - // yoffset non-zero indicates that the most common scroll wheel is changing. If there's - // a second scroll wheel, xoffset will be passed non-zero. They'll be 0 or +/- 1. - - if (this->state.test (visual_state::sceneLocked)) { return false; } - - this->savedSceneview = this->sceneview; - this->savedSceneview_tr = this->sceneview_tr; - this->scenetrans_delta.zero(); - this->rotation_delta.reset(); - this->state.set (visual_state::scrolling); - - if (this->ptype == perspective_type::orthographic) { - // In orthographic, the wheel should scale ortho_lb and ortho_rt - sm::vec _lb = this->ortho_lb + (yoffset * this->scenetrans_stepsize); - sm::vec _rt = this->ortho_rt - (yoffset * this->scenetrans_stepsize); - if (_lb < 0.0f && _rt > 0.0f) { - this->ortho_lb = _lb; - this->ortho_rt = _rt; - } - - } else { // perspective_type::perspective - - // xoffset does what mouse drag left/right in rotateModMode does (L/R scene trans) - this->scenetrans_delta[0] -= xoffset * this->scenetrans_stepsize; - - // yoffset does the 'in-out zooming' - - // How to make scenetrans_stepsize adaptive to the scale of the environment and change when close to objects? - float y_step = static_cast(yoffset) * this->scenetrans_stepsize * this->d_to_rotation_centre; - sm::vec scroll_move_y = { 0.0f, y_step, 0.0f, 1.0f }; - - this->scenetrans_delta[2] += scroll_move_y[1]; - - if (this->d_to_rotation_centre > (this->zFar / 2.0f) && scroll_move_y[1] < 0.0f) { - // Cancel movement - this->scenetrans_delta[2] = 0.0f; - scroll_move_y[1] = 0.0f; - } - - this->d_to_rotation_centre -= this->scenetrans_delta[2]; - } - return true; // needs_render - } - - virtual void key_callback_extra ([[maybe_unused]] std::int32_t key, [[maybe_unused]] std::int32_t scancode, - [[maybe_unused]] std::int32_t action, [[maybe_unused]] std::int32_t mods) {} - - virtual void mouse_button_callback_extra ([[maybe_unused]] std::int32_t button, [[maybe_unused]] std::int32_t action, - [[maybe_unused]] std::int32_t mods) {} - - //! A callback that client code can set so that it knows when user has signalled to - //! mplot::Visual that it's quit time. - std::function external_quit_callback; - - protected: - //! This internal quit function sets a 'readyToFinish' flag that your code can respond to, - //! and calls an external callback function that you may have set up. - void signal_to_quit() - { - if (this->options.test (visual_options::userInfoStdout)) { std::cout << "User requested exit.\n"; } - // 1. Set our 'readyToFinish' flag to true - this->state.set (visual_state::readyToFinish); - // 2. Call any external callback that's been set by client code - if (this->external_quit_callback) { this->external_quit_callback(); } - } - - //! Unpause, allowing pauseOpen() to return - void unpause() { this->state.reset (visual_state::paused); } - }; - -} // namespace mplot diff --git a/mplot/VisualResources.cppm b/mplot/VisualResources.cppm deleted file mode 100644 index 9681def8..00000000 --- a/mplot/VisualResources.cppm +++ /dev/null @@ -1,377 +0,0 @@ -/*! - * \file - * - * Declares a VisualResource class to hold the information about Freetype which is a one-per-program - * resource. Also holds the Glad contexts - the OpenGL function pointers for each window. Windows - * are referred to as mplot::win_t; the identity of win_t (which might be GLFWwindow or - * QtOpenGLWidget) is abstact in this file. - * - * \author Seb James - * \date November 2020 - */ -module; - -// Include GLAD header -#include - -// FreeType for text rendering -#include -#include FT_FREETYPE_H - -#include -#include -#include -#include -#include -#include - -export module mplot.visualresources; - -import mplot.visualcommon; -import mplot.visualface; -import mplot.visualfont; -import mplot.textfeatures; -import mplot.win_t; -import mplot.gl.version; -import mplot.gl.util; -import sm.vec; - -export namespace mplot -{ - //! Singleton resource class for mplot::Visual scenes. - template - class VisualResources - { - private: - VisualResources(){} - ~VisualResources() - { - this->faces.clear(); - // As with the case for faces, when each mplot::Visual goes out of scope, the FreeType - // instance gets cleaned up. So at this stage freetypes should also be empy and nothing - // will happen here either. - for (auto& ft : this->freetypes) { FT_Done_FreeType (ft.second); } - } - - //! The collection of VisualFaces generated for this instance of the application. Create one - //! VisualFace for each unique combination of VisualFont and fontpixels (the texture - //! resolution). uint32_t is the 'visual_id' an ID of the Visual instance. - std::map, - std::unique_ptr> faces; - - //! FreeType library object. Keyed by the 'visual_id' an ID of the Visual instance. - std::map freetypes; - - public: - VisualResources(const VisualResources&) = delete; - VisualResources& operator=(const VisualResources &) = delete; - VisualResources(VisualResources &&) = delete; - VisualResources & operator=(VisualResources &&) = delete; - - //! Initialize a freetype library instance and add to this->freetypes. I wanted - //! to have only a single freetype library instance, but this didn't work, so I - //! create one FT_Library for each OpenGL context (i.e. one for each mplot::Visual - //! window). Thus, arguably, the FT_Library should be a member of mplot::Visual, - //! but that's a task for the future, as I coded it this way under the false - //! assumption that I'd only need one FT_Library. - void freetype_init (std::uint32_t _vis, GladGLContext* glfn = nullptr) - { - FT_Library freetype = nullptr; - try { - freetype = this->freetypes.at (_vis); - } catch (const std::out_of_range&) { - // Use of gl calls here may make it neat to set up GL here in VisualResources? - glfn->PixelStorei(GL_UNPACK_ALIGNMENT, 1); // disable byte-alignment restriction - mplot::gl::Util::checkError (__FILE__, __LINE__, glfn); - - if (FT_Init_FreeType (&freetype)) { - std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl; - } else { - // Successfully initialized freetype - this->freetypes[_vis] = freetype; - } - } - } - - //! When a mplot::Visual goes out of scope, its freetype library instance should be - //! deinitialized. - void freetype_deinit (std::uint32_t _vis) - { - // First clear the faces associated with Visual with ID _vis - this->clearVisualFaces (_vis); - // Second, clean up the FreeType library instance and erase from this->freetypes - auto freetype = this->freetypes.find (_vis); - if (freetype != this->freetypes.end()) { - FT_Done_FreeType (freetype->second); - this->freetypes.erase (freetype); - } - } - - //! The instance public function. Uses the very short name 'i' to keep code tidy. - //! This relies on C++11 magic statics (N2660). - static auto& i() - { - static VisualResources instance; - return instance; - } - - //! A function to call to simply make sure the singleton instance exists - void create() {} - - //! Return a pointer to a VisualFace for the given \a font at the given texture - //! resolution, \a fontpixels and the given window (i.e. OpenGL context) \a _win. - mplot::visgl::VisualFace* getVisualFace (mplot::VisualFont font, std::uint32_t fontpixels, - std::uint32_t _vis, GladGLContext* glfn) - { - mplot::visgl::VisualFace* rtn = nullptr; - auto key = std::make_tuple(font, fontpixels, _vis); - try { - rtn = this->faces.at(key).get(); - } catch (const std::out_of_range&) { - this->faces[key] = std::make_unique (font, fontpixels, this->freetypes.at(_vis), glfn); - rtn = this->faces.at(key).get(); - } - return rtn; - } - - mplot::visgl::VisualFace* getVisualFace (const mplot::TextFeatures& tf, - const std::uint32_t _vis, GladGLContext* glfn) - { - return this->getVisualFace (tf.font, tf.fontres, _vis, glfn); - } - - //! Loop through this->faces clearing out those associated with the given mplot::Visual - void clearVisualFaces (const std::uint32_t _vis) - { - mplot::VisualFont thefont; - std::uint32_t fpixels = 0; - std::uint32_t vf_vis = std::numeric_limits::max(); - - auto f = this->faces.begin(); - - while (f != this->faces.end()) { - // f->first is a key. If its third, visual_id element == _vis, then delete and erase - // f->first needs unpacking; want 3rd elemetn - std::tie(thefont, fpixels, vf_vis) = f->first; - - if (vf_vis == _vis) { - f = this->faces.erase (f); - } else { f++; } - } - } - - std::uint32_t next_visual_id = 0; - - // GL function context pointers used in the program, keyed by a uint32_t ID - std::map visual_keyed_gladglcontexts; - // GL shader programs used by Visual in the program, keyed by ID - std::map visual_keyed_shaderprogs; - // Window contexts - std::map visual_keyed_windows; - // Does instanced data need update? - std::map visual_keyed_instanced_needs_update; - - std::uint32_t register_visual (GladGLContext* glfn, mplot::win_t* win) - { - std::uint32_t visual_id = this->next_visual_id++; - this->visual_keyed_gladglcontexts[visual_id] = glfn; - this->visual_keyed_shaderprogs[visual_id] = {}; // initialized empty with 0s - this->visual_keyed_windows[visual_id] = win; - this->visual_keyed_instanced_needs_update[visual_id] = false; - return visual_id; - } - - // Return true if there is a GladGLContext for visual_id - bool test_glfn (const std::uint32_t visual_id) - { - if (visual_id == std::numeric_limits::max()) { - return false; - } - try { - [[maybe_unused]] GladGLContext* glfn = this->visual_keyed_gladglcontexts.at (visual_id); - return true; - } catch (const std::exception& e) {} - return false; - } - - /*! - * A VisualModel can call this method, passing in the numeric ID of the context it belongs - * to. The return value will be the correct GL context pointer. - */ - GladGLContext* get_glfn (const std::uint32_t visual_id) noexcept - { - if (visual_id == std::numeric_limits::max()) { return nullptr; } - GladGLContext* glfn = this->visual_keyed_gladglcontexts[visual_id]; - return glfn; - } - - void set_tprog (const std::uint32_t visual_id, const std::uint32_t _tprog) - { - if (visual_id == std::numeric_limits::max()) { - throw std::runtime_error ("VisualResources::set_tprog(): visual_id is unset"); - } - this->visual_keyed_shaderprogs[visual_id].tprog = _tprog; - } - - std::uint32_t get_tprog (const std::uint32_t visual_id) - { - if (visual_id == std::numeric_limits::max()) { - throw std::runtime_error ("VisualResources::get_tprog(): visual_id is unset"); - } - return this->visual_keyed_shaderprogs[visual_id].tprog; - } - - void set_gprog (const std::uint32_t visual_id, const std::uint32_t _gprog) - { - if (visual_id == std::numeric_limits::max()) { - throw std::runtime_error ("VisualResources::set_gprog(): visual_id is unset"); - } - this->visual_keyed_shaderprogs[visual_id].gprog = _gprog; - } - - std::uint32_t get_gprog (const std::uint32_t visual_id) - { - if (visual_id == std::numeric_limits::max()) { - throw std::runtime_error ("VisualResources::get_gprog(): visual_id is unset"); - } - return this->visual_keyed_shaderprogs[visual_id].gprog; - } - - /*! - * Set the window context. This has to be window-system agnostic here, so we have the - * std::function setContext_implementation that (if you are using GLFW windows) is linked at - * runtime to VisualGlfw::setContext(GLFWwindow*) - */ - void setContext (const std::uint32_t visual_id) - { - if (visual_id == std::numeric_limits::max()) { - throw std::runtime_error ("VisualResources::setContext(): visual_id is unset"); - } - if (this->setContext_implementation) { - this->setContext_implementation (this->visual_keyed_windows[visual_id]); - } - } - - //! setContext function call object - std::function setContext_implementation; - - //! Window-system agnostic releaseContext call (see also setContext) - void releaseContext() { if (this->releaseContext_implementation) { this->releaseContext_implementation(); } } - - //! releaseContext function call object - std::function releaseContext_implementation; - - bool get_instanced_needs_update (const std::uint32_t visual_id) - { - if (visual_id == std::numeric_limits::max()) { - throw std::runtime_error ("VisualResources::get_instanced_needs_update: visual_id is unset"); - } - return this->visual_keyed_instanced_needs_update[visual_id]; - } - - void instanced_needs_update (const std::uint32_t visual_id, const bool val = true) - { - if (visual_id == std::numeric_limits::max()) { - throw std::runtime_error ("VisualResources::instanced_needs_update: visual_id is unset"); - } - this->visual_keyed_instanced_needs_update[visual_id] = val; - } - - /*! - * We also manage some programm-wide SSBO objects for instanced rendering - * VisualResourcesdata in . Reserve n_to_reserve instances of data in the SSBOs. Return the - * start offset into the buffers in terms of number of instances - */ - std::uint32_t init_instance_ssbo (const std::uint32_t visual_id, const std::uint32_t n_to_reserve) - { - GladGLContext* glfn = this->get_glfn (visual_id); - std::uint32_t reservation = std::numeric_limits::max(); - if constexpr (mplot::gl::version::has_ssbo (glver) == true) { - if (this->instance_data.ready() == false) { this->instance_data.init (glfn); } - if (this->instparam_data.ready() == false) { this->instparam_data.init (glfn); } - if (n_to_reserve + this->instance_top <= this->max_instances) { - reservation = this->instance_top; - this->instance_top += n_to_reserve; - this->instance_data.resize (this->instance_top * this->floats_per_instance, 1000.0f); - this->instparam_data.resize (this->instance_top * this->floats_per_instparam); - } - } else { - throw std::runtime_error ("Instanced rendering requires OpenGL 4.3 or higher"); - } - return reservation; - } - - /*! - * Inserts the 3 values from coord into the SSBO instance buffer, starting at location - * instance_idx - */ - void insert_instance_data (const std::uint32_t instance_idx, const sm::vec& coord) - { - // If this function fails, make sure to call v.render before calling set_instance_data :) - if (instance_idx >= this->max_instances) { - throw std::runtime_error ("insert_instance_data: bad instance_idx"); - } - std::uint32_t cur_fidx = instance_idx * this->floats_per_instance; - this->instance_data.data[cur_fidx++] = coord[0]; - this->instance_data.data[cur_fidx++] = coord[1]; - this->instance_data.data[cur_fidx++] = coord[2]; - } - - /*! - * Inserts the 3 values from colour, along with alpha and scale into the SSBO instparam - * buffer, starting at location instance_idx - */ - void insert_instparam_data (const std::uint32_t instance_idx, - const std::array& colour, const float& alpha, const float& scale) - { - if (instance_idx >= this->max_instances) { - throw std::runtime_error ("insert_instparam_data: bad instance_idx"); - } - std::uint32_t cur_fidx = instance_idx * this->floats_per_instparam; - this->instparam_data.data[cur_fidx++] = colour[0]; - this->instparam_data.data[cur_fidx++] = colour[1]; - this->instparam_data.data[cur_fidx++] = colour[2]; - this->instparam_data.data[cur_fidx++] = alpha; - this->instparam_data.data[cur_fidx++] = scale; - } - - void copy_instance_ssbo_to_gpu() - { - if (this->instance_data.ready()) { this->instance_data.copy_to_gpu(); } - if (this->instparam_data.ready()) { this->instparam_data.copy_to_gpu(); } - } - - /*! - * SSBO management - */ - //! Instanced rendering mode (SSBO access). position data stored in SSBO index 1 (must match GLSL code) - static constexpr std::uint32_t instance_index = 1u; - //! colour, scale, rotation stored in SSBO index 2 - static constexpr std::uint32_t instparam_index = 2u; - //! one 3D vector is 3 floats - static constexpr std::uint32_t floats_per_instance = 3u; - //! Instance params are: colour/alpha (4 floats), scale (1 float) - static constexpr std::uint32_t floats_per_instparam = 5u; - - /*! - * This will control how much GPU RAM is allocated when using instanced rendering - * (Hopefully, when I'm finished, the RAM will be allocated only if at least one VisualModel - * is marked 'instanced'). Makes a big difference to speed of operation (unless I can send a - * portion of a buffer to the GPU). - */ - static constexpr std::uint32_t max_instances = 32u * 1024u; - static constexpr std::uint32_t max_instance_floats = floats_per_instance * max_instances; - static constexpr std::uint32_t max_instparam_floats = floats_per_instparam * max_instances; - - //! Shader Storage Buffer Object for instanced rendering - this holds positions only - mplot::gl::ssbo::instance_index, - float, mplot::VisualResources::max_instance_floats> instance_data; - //! Shader Storage Buffer Object for instanced rendering - this holds colour, alpha and scale - mplot::gl::ssbo::instparam_index, - float, mplot::VisualResources::max_instparam_floats> instparam_data; - - // The Current location from which space in the instance SSBOs should be allocated - std::uint32_t instance_top = 0; - }; - -} // namespace mplot diff --git a/mplot/VisualTextModel.cppm b/mplot/VisualTextModel.cppm deleted file mode 100644 index 1dc1d225..00000000 --- a/mplot/VisualTextModel.cppm +++ /dev/null @@ -1,551 +0,0 @@ -/*! - * \file - * - * Declares a class to hold vertices of the quads that are the backing for a sequence of text - * characters. This is for use in VisualModel-derived classes. Within the backend, the - * VisualTextModel classes are used directly. - * - * \author Seb James - * \date Oct 2020 - Mar 2026 - */ -module; - -#if defined __gl3_h_ || defined __gl_h_ -// GL headers have been externally included -#else -# include -#endif - -#include -#include -#include -#include -#include -#include -#include - -export module mplot.visualtextmodel; - -import mplot.visualresources; -import mplot.visualcommon; -export import mplot.textgeometry; -export import mplot.textfeatures; -export import mplot.unicode; -export import mplot.visualface; -import mplot.colour; -import mplot.gl.version; -import mplot.gl.util; - -import sm.mathconst; -import sm.quaternion; -import sm.mat; -import sm.vec; - -export namespace mplot -{ - /*! - * This is the base class for VisualTextModel containing common code, but no GL function calls. - */ - template - struct VisualTextModel - { - public: - VisualTextModel (mplot::TextFeatures _tf) - { - this->tf = _tf; - this->fontscale = tf.fontsize / static_cast(tf.fontres); - } - - ~VisualTextModel() - { - if (this->vbos != nullptr) { - // To be a visualresources get - GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - _glfn->DeleteBuffers (this->numVBO, this->vbos.get()); - _glfn->DeleteVertexArrays (1, &this->vao); - } - } - - //! Render the VisualTextModel - void render() - { - if (this->hide == true) { return; } - - std::int32_t prev_shader; - std::uint32_t tshaderprog = mplot::VisualResources::i().get_tprog (this->parentVis); - GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - - _glfn->GetIntegerv (GL_CURRENT_PROGRAM, &prev_shader); - - // Ensure the correct program is in play for this VisualModel - _glfn->UseProgram (tshaderprog); - - // Set uniforms - std::int32_t loc_tc = _glfn->GetUniformLocation (tshaderprog, static_cast("textColor")); - if (loc_tc != -1) { _glfn->Uniform3f (loc_tc, this->clr_text[0], this->clr_text[1], this->clr_text[2]); } - std::int32_t loc_a = _glfn->GetUniformLocation (tshaderprog, static_cast("alpha")); - if (loc_a != -1) { _glfn->Uniform1f (loc_a, this->alpha); } - std::int32_t loc_v = _glfn->GetUniformLocation (tshaderprog, static_cast("v_matrix")); - if (loc_v != -1) { _glfn->UniformMatrix4fv (loc_v, 1, GL_FALSE, this->scenematrix.arr.data()); } - std::int32_t loc_m = _glfn->GetUniformLocation (tshaderprog, static_cast("m_matrix")); - if (loc_m != -1) { _glfn->UniformMatrix4fv (loc_m, 1, GL_FALSE, this->viewmatrix.arr.data()); } - - _glfn->ActiveTexture (GL_TEXTURE0); - - // It is only necessary to bind the vertex array object before rendering - _glfn->BindVertexArray (this->vao); - - // We have a max of (2^32)-1 characters. Should be enough. - for (std::uint32_t i = 0U; i < this->quads.size(); ++i) { - // Bind the right texture for the quad. - _glfn->BindTexture (GL_TEXTURE_2D, this->quad_ids[i]); - // This is 'draw a subset of the elements from the vertex array - // object'. You say how many indices to draw and which base *vertex* you - // start from. In my scheme, I have 4 vertices for each two triangles - // that are constructed. Thus, I draw 6 indices, but increment the base - // vertex by 4 for each letter. - _glfn->DrawElementsBaseVertex (GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, 4*i); - } - - _glfn->BindVertexArray(0); - _glfn->UseProgram (prev_shader); - - mplot::gl::Util::checkError (__FILE__, __LINE__, _glfn); - } - - //! Compute the geometry for a sample text. - mplot::TextGeometry getTextGeometry (const std::string& _txt) - { - mplot::TextGeometry geom; - - if (!mplot::VisualResources::i().test_glfn (this->parentVis)) { return geom; } - if (this->face == nullptr) { - GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - this->face = VisualResources::i().getVisualFace (this->tf, this->parentVis, _glfn); - } - - // First convert string from ASCII/UTF-8 into Unicode. - std::basic_string utxt = mplot::unicode::fromUtf8(_txt); - // on g++ 15 there's an issue with operator!= when used in a module - for (std::basic_string::const_iterator c = utxt.cbegin(); c != utxt.cend(); c++) { - mplot::visgl::CharInfo ci = this->face->glchars[*c]; - float drop = (ci.size.y() - ci.bearing.y()) * this->fontscale; - geom.max_drop = (drop > geom.max_drop) ? drop : geom.max_drop; - float bearingy = ci.bearing.y() * this->fontscale; - geom.max_bearingy = (bearingy > geom.max_bearingy) ? bearingy : geom.max_bearingy; - geom.total_advance += ((ci.advance>>6)*this->fontscale); - } - return geom; - } - - //! Return the geometry for the stored txt - mplot::TextGeometry getTextGeometry() - { - mplot::TextGeometry geom; - - if (!mplot::VisualResources::i().test_glfn (this->parentVis)) { return geom; } - if (this->face == nullptr) { - GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - this->face = VisualResources::i().getVisualFace (this->tf, this->parentVis, _glfn); - } - - for (std::basic_string::const_iterator c = this->txt.begin(); c != this->txt.end(); c++) { - mplot::visgl::CharInfo ci = this->face->glchars[*c]; - float drop = (ci.size.y() - ci.bearing.y()) * this->fontscale; - geom.max_drop = (drop > geom.max_drop) ? drop : geom.max_drop; - float bearingy = ci.bearing.y() * this->fontscale; - geom.max_bearingy = (bearingy > geom.max_bearingy) ? bearingy : geom.max_bearingy; - geom.total_advance += ((ci.advance>>6)*this->fontscale); - } - return geom; - } - - //! Set up a new text at a given position, with the given colour. - void setupText (const std::string& _txt, - const sm::vec _offset, std::array _clr = {0,0,0}) - { - this->viewmatrix.translate (_offset); - this->clr_text = _clr; - this->setupText (_txt); - } - - //! Set up a new text at a given position, with the given colour and a pre-rotation - void setupText (const std::string& _txt, - const sm::quaternion& _rotation, const sm::vec _offset, - std::array _clr = {0,0,0}) - { - this->viewmatrix.translate (_offset); - this->viewmatrix.rotate (_rotation); - this->clr_text = _clr; - this->setupText (_txt); - } - - void setupText (const std::string& _txt) - { - // Convert std::string _txt to std::basic_string text and call the other setupText - this->setupText (mplot::unicode::fromUtf8 (_txt)); - } - - //! With the given text and font size information, create the quads for the text. - void setupText (const std::basic_string& _txt) - { - constexpr bool debug_textquads = false; - - if (this->face == nullptr) { - GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - this->face = VisualResources::i().getVisualFace (this->tf, this->parentVis, _glfn); - } - - this->txt = _txt; - // With glyph information from txt, set up this->quads. - this->quads.clear(); - this->quad_ids.clear(); - // Our string of letters starts at this location - float letter_pos = 0.0f; - float letter_y = 0.0f; - float text_epsilon = 0.0f; - for (std::basic_string::const_iterator c = this->txt.begin(); c != this->txt.end(); c++) { - - if (*c == '\n') { - // Skip newline, but add a y offset and reset letter_pos - letter_pos = 0.0f; - mplot::visgl::CharInfo ch = this->face->glchars['h']; - letter_y += this->line_spacing * -ch.size.y() * this->fontscale; - continue; - } - - // Add a quad to this->quads - mplot::visgl::CharInfo ci = this->face->glchars[*c]; - - float xpos = letter_pos + ci.bearing.x() * this->fontscale; - float ypos = letter_y - (ci.size.y() - ci.bearing.y()) * this->fontscale; - float w = ci.size.x() * this->fontscale; - float h = ci.size.y() * this->fontscale; - - // Update extents - if (xpos < this->extents[0]) { this->extents[0] = xpos; } // left - if (xpos+w > this->extents[1]) { this->extents[1] = xpos+w; } // right - if (ypos < this->extents[2]) { this->extents[2] = ypos; } // bottom - if (ypos+h > this->extents[3]) { this->extents[3] = ypos+h; } // top - - // What's the order of the vertices for the quads? It is: - // Bottom left, Top left, top right, bottom right. - std::array tbox = { xpos, ypos, text_epsilon, - xpos, ypos+h, text_epsilon, - xpos+w, ypos+h, text_epsilon, - xpos+w, ypos, text_epsilon }; - text_epsilon -= 10.0f * std::numeric_limits::epsilon(); - if constexpr (debug_textquads == true) { - std::cout << "Text box added as quad from\n(" - << tbox[0] << "," << tbox[1] << "," << tbox[2] - << ") to (" << tbox[3] << "," << tbox[4] << "," << tbox[5] - << ") to (" << tbox[6] << "," << tbox[7] << "," << tbox[8] - << ") to (" << tbox[9] << "," << tbox[10] << "," << tbox[11] - << "). w="<quads.push_back (tbox); - this->quad_ids.push_back (ci.textureID); - - // The value in ci.advance has to be divided by 64 to bring it into the - // same units as the ci.size and ci.bearing values. - letter_pos += ((ci.advance>>6)*this->fontscale); - } - - // Ensure we've cleared out vertex info - this->vertexPositions.clear(); - this->vertexNormals.clear(); - this->vertexColors.clear(); - this->vertexTextures.clear(); - this->indices.clear(); - - this->initializeVertices(); - - this->postVertexInit(); - } - - protected: - - //! Common code to call after the vertices have been set up. - void postVertexInit() - { - GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - if (this->vbos == nullptr) { - // Create vertex array object - _glfn->GenVertexArrays (1, &this->vao); // Safe for OpenGL 4.4- - } - - _glfn->BindVertexArray (this->vao); - - if (this->vbos == nullptr) { - // Create the vertex buffer objects - this->vbos = std::make_unique(this->numVBO); - _glfn->GenBuffers (this->numVBO, this->vbos.get()); // OpenGL 4.4- safe - } - - // Set up the indices buffer - bind and buffer the data in this->indices - _glfn->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->vbos[this->idxVBO]); - - //std::cout << "indices.size(): " << this->indices.size() << std::endl; - std::size_t sz = this->indices.size() * sizeof(std::uint32_t); - _glfn->BufferData(GL_ELEMENT_ARRAY_BUFFER, sz, this->indices.data(), GL_STATIC_DRAW); - - // Binds data from the "C++ world" to the OpenGL shader world for - // "position", "normalin" and "color" - // (bind, buffer and set vertex array object attribute) - this->setupVBO (this->vbos[this->posnVBO], this->vertexPositions, visgl::posnLoc); - this->setupVBO (this->vbos[this->normVBO], this->vertexNormals, visgl::normLoc); - this->setupVBO (this->vbos[this->colVBO], this->vertexColors, visgl::colLoc); - this->setupVBO (this->vbos[this->textureVBO], this->vertexTextures, visgl::textureLoc); - - // Possibly release (unbind) the vertex buffers, but have to unbind vertex - // array object first. - _glfn->BindVertexArray(0); // carefully unbind - } - - //! A face for this text. The face is specfied by tf.font - mplot::visgl::VisualFace* face = nullptr; - - //! Set up a vertex buffer object - bind, buffer and set vertex array object attribute - void setupVBO (std::uint32_t& buf, std::vector& dat, std::uint32_t bufferAttribPosition) - { - std::size_t sz = dat.size() * sizeof(float); - GladGLContext* _glfn = mplot::VisualResources::i().get_glfn (this->parentVis); - _glfn->BindBuffer (GL_ARRAY_BUFFER, buf); - _glfn->BufferData (GL_ARRAY_BUFFER, sz, dat.data(), GL_STATIC_DRAW); - _glfn->VertexAttribPointer (bufferAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, (void*)(0)); - _glfn->EnableVertexAttribArray (bufferAttribPosition); - } - - public: - //! Set clr_text to a value suitable to be visible on the background colour bgcolour - void setVisibleOn (const std::array& bgcolour) - { - constexpr float factor = 0.85f; - this->clr_text = {1.0f - bgcolour[0] * factor, 1.0f - bgcolour[1] * factor, 1.0f - bgcolour[2] * factor}; - } - - //! Setter for VisualTextModel::viewmatrix, the model view - void setViewMatrix (const sm::mat& mv) { this->viewmatrix = mv; } - - //! Setter for VisualTextModel::scenematrix, the scene view - void setSceneMatrix (const sm::mat& sv) { this->scenematrix = sv; } - - //! Set the translation specified by \a v0 into the scene translation - template requires (N == 3) || (N == 4) - void setSceneTranslation (const sm::vec& v0) - { - this->scenematrix.set_identity(); - this->scenematrix.translate (v0); - } - - //! Set a translation (only) into the scene view matrix - template requires (N == 3) || (N == 4) - void addSceneTranslation (const sm::vec& v0) { this->scenematrix.pretranslate (v0); } - - //! Set a rotation (only) into the scene view matrix - void setSceneRotation (const sm::quaternion& r) - { - auto _offset = this->scenematrix.translation(); - this->scenematrix.set_identity(); - this->scenematrix.translate (_offset); - this->scenematrix.rotate (r); - } - - //! Add a rotation to the scene view matrix - void addSceneRotation (const sm::quaternion& r) { this->scenematrix.rotate (r); } - - //! Set a translation to the model view matrix - template requires (N == 3) || (N == 4) - void setViewTranslation (const sm::vec& v0) - { - this->viewmatrix.set_identity(); - this->viewmatrix.translate (v0); - } - - //! Add a translation to the model view matrix - void addViewTranslation (const sm::vec& v0) { this->viewmatrix.pretranslate (v0); } - - //! Set a rotation (only) into the model view matrix - void setViewRotation (const sm::quaternion& r) - { - auto tr = this->viewmatrix.translation(); - this->viewmatrix.set_identity(); - this->viewmatrix.translate (tr); - this->viewmatrix.rotate (r); - } - - //! Apply a further rotation to the model view matrix - void addViewRotation (const sm::quaternion& r) { this->viewmatrix.rotate (r); } - - - float width() const { return this->extents[1] - this->extents[0]; } - float height() const { return this->extents[3] - this->extents[2]; } - - std::string getText() const - { - std::string s = {}; - for (auto c : txt) { s += unicode::toUtf8 (c); } - return s; - } - - std::string debugText() const { return this->getText(); } - - protected: - - //! Initialize the vertices that will represent the Quads. - void initializeVertices() { - - constexpr bool debug_textquads = false; - - std::uint32_t nquads = static_cast(this->quads.size()); - - for (std::uint32_t qi = 0; qi < nquads; ++qi) { - - std::array quad = this->quads[qi]; - - if constexpr (debug_textquads == true) { - std::cout << "Quad box from (" << quad[0] << "," << quad[1] << "," << quad[2] - << ") to (" << quad[3] << "," << quad[4] << "," << quad[5] - << ") to (" << quad[6] << "," << quad[7] << "," << quad[8] - << ") to (" << quad[9] << "," << quad[10] << "," << quad[11] << ")" << std::endl; - } - - this->vertex_push (quad[0], quad[1], quad[2], this->vertexPositions); //1 - this->vertex_push (quad[3], quad[4], quad[5], this->vertexPositions); //2 - this->vertex_push (quad[6], quad[7], quad[8], this->vertexPositions); //3 - this->vertex_push (quad[9], quad[10], quad[11], this->vertexPositions); //4 - - // Add the info for drawing the textures on the quads - this->vertex_push (0.0f, 1.0f, 0.0f, this->vertexTextures); - this->vertex_push (0.0f, 0.0f, 0.0f, this->vertexTextures); - this->vertex_push (1.0f, 0.0f, 0.0f, this->vertexTextures); - this->vertex_push (1.0f, 1.0f, 0.0f, this->vertexTextures); - - // All same colours - this->vertex_push (this->clr_backing, this->vertexColors); - this->vertex_push (this->clr_backing, this->vertexColors); - this->vertex_push (this->clr_backing, this->vertexColors); - this->vertex_push (this->clr_backing, this->vertexColors); - - // All same normals - this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); - this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); - this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); - this->vertex_push (0.0f, 0.0f, 1.0f, this->vertexNormals); - - // Two triangles per quad - // qi * 4 + 1, 2 3 or 4 - std::uint32_t ib = static_cast(qi) * 4u; - this->indices.push_back (ib++); // 0 - this->indices.push_back (ib++); // 1 - this->indices.push_back (ib); // 2 - - this->indices.push_back (ib++); // 2 - this->indices.push_back (ib); // 3 - ib -= 3; - this->indices.push_back (ib); // 0 - } - } - - public: - // A VisualTextModel may be given a name - std::string name = "VisualTextModel"; - - //! The colour of the text - std::array clr_text = {0.0f, 0.0f, 0.0f}; - //! Line spacing, in multiples of the height of an 'h' - float line_spacing = 1.4f; - //! Parent Visual. The mplot::Visual ID to which I belong. max means unset. - std::uint32_t parentVis = std::numeric_limits::max(); - - //! Setter for the parent pointer, parentVis - void set_parent (const std::uint32_t _vis) - { - if (this->parentVis != std::numeric_limits::max()) { - throw std::runtime_error ("VisualTextModel: Set the parent pointer once only!"); - } - this->parentVis = _vis; - } - - protected: - // The text features for this VisualTextModel - mplot::TextFeatures tf; - - // face is in derived class - - //! The colour of the backing quad's vertices. Doesn't have any effect. - std::array clr_backing = {1.0f, 1.0f, 0.0f}; - - //! A scaling factor based on the desired width of an 'm' - float fontscale = 1.0f; // fontscale = tf.fontsize/(float)tf.fontres; - - //! A rotation of the parent model - sm::quaternion parent_rotation = {}; - - //! The text-model-specific view matrix and a scene matrix - sm::mat viewmatrix = sm::mat::identity(); - //! Before, I wrote: We protect the scene matrix as updating it with the parent - //! model's scene matrix likely involves also adding an additional - //! translation. Now, I'm still slightly confused as to whether I *need* to have a - //! copy of the scenematrix *here*. - sm::mat scenematrix = sm::mat::identity(); - - //! The text string stored for debugging - std::basic_string txt; - //! The Quads that form the 'medium' for the text textures. 12 float = 4 corners - std::vector> quads = {}; - //! left, right, top and bottom extents of the text for this - //! VisualTextModel. setupText should modify these as it sets up quads. Order of - //! numbers is left, right, bottom, top - sm::vec extents = { 1e7, -1e7, 1e7, -1e7 }; - //! The texture ID for each quad - so that we draw the right texture image over each quad. - std::vector quad_ids = {}; - //! Position within vertex buffer object (if I use an array of VBO) - enum VBOPos { posnVBO, normVBO, colVBO, idxVBO, textureVBO, numVBO }; - //! The OpenGL Vertex Array Object - std::uint32_t vao = 0; - //! Single vbo to use as in example - std::uint32_t vbo = 0; - //! Vertex Buffer Objects stored in an array - std::unique_ptr vbos; - //! CPU-side data for indices - std::vector indices = {}; - //! CPU-side data for quad vertex positions - std::vector vertexPositions = {}; - //! CPU-side data for quad vertex normals - std::vector vertexNormals = {}; - //! CPU-side data for vertex colours - std::vector vertexColors = {}; - //! data for textures - std::vector vertexTextures = {}; - //! A model-wide alpha value for the shader - float alpha = 1.0f; - //! If true, then calls to VisualModel::render should return - bool hide = false; - - //! Push three floats onto the vector of floats \a vp - void vertex_push (const float& x, const float& y, const float& z, std::vector& vp) - { - vp.emplace_back (x); - vp.emplace_back (y); - vp.emplace_back (z); - } - //! Push array of 3 floats onto the vector of floats \a vp - void vertex_push (const std::array& arr, std::vector& vp) - { - vp.emplace_back (arr[0]); - vp.emplace_back (arr[1]); - vp.emplace_back (arr[2]); - } - //! Push mplot::vec of 3 floats onto the vector of floats \a vp - template requires (N == 3 || N == 4) - void vertex_push (const sm::vec& vec, std::vector& vp) - { - vp.emplace_back (vec[0]); - vp.emplace_back (vec[1]); - vp.emplace_back (vec[2]); - } - }; - -} // namespace mplot