8. Dessiner à la souris
Dans cet exemple, des traits sont dessinés à la souris sur une feuille. La démo a ses propres touches (annuler, effacer, changer de couleur), et la slide a des boutons pour les mêmes actions. L'intérêt de l'exemple tient au clavier : les touches de la démo ne doivent pas prendre celles de la présentation.
Télécharger : c8-cgp-sketch.zip. Le zip contient le programme C++, sa slide en reveal.js (slides.html) et en lhtml-site (lhtml-site/), la compilation web de la démo (prête à montrer), le pont et le script de compilation. Le projet CGP n'est nécessaire que pour recompiler.
L'essayer : décompressez-le, et dans le dossier décompressé lancez python3 -m http.server 8080 ; puis ouvrez http://localhost:8080/examples/c8-cgp-sketch/slides.html, la slide avec sa démo. Pour modifier le programme : compiler et lancer.
Ce qui est nouveau
- Des touches propres à la démo : le programme lit ses touches dans
keyboard_event(). Utilisez des lettres et des chiffres : la page de la démo envoie les flèches et Page Down / Page Up aux slides, même après un clic dans la démo, pour que la présentation les garde. Évitez la barre d'espace, que certains outils de slides utilisent aussi. - Les codes des touches : sur le web, comparez les codes GLFW (
key == GLFW_KEY_Z) : les noms des touches (glfwGetKeyName) ne sont pas connus dans un navigateur. - Une touche et un bouton pour la même action : les touches appellent
slide::set("undo", ""), qui change un paramètre ou lance une action comme le font les boutons de la slide (pour une action, la valeur est vide ; voir la référence) ; après un changement fait par le programme,slide::notify()permet au panneau et à la slide d'afficher les nouvelles valeurs. - Des traits larges : WebGL dessine les lignes sur un pixel de large. Chaque trait est un ruban, un maillage reconstruit pendant le mouvement de la souris, aussi large que voulu.
- Une image pour le PDF :
?sample=1démarre avec une spirale déjà dessinée ; le poster de la démo est pris avec elle.
Compiler et lancer
Comme l'exemple 3, avec c8-cgp-sketch.
Les fichiers
src/scene.cpp
Afficher le fichier complet : scene.cpp (193 lignes)
#include "scene.hpp" #include "slide_bridge.hpp" #include <cmath> using namespace cgp; void scene_structure::initialize() { camera_control.initialize(inputs, window); camera_control.set_rotation_axis_z(); camera_control.look_at({0, -0.01f, 3.0f}, {0, 0, 0}, {0, 1, 0}); // facing the sheet sheet.initialize_data_on_gpu(mesh_primitive_quadrangle({-1.6f, -1, -0.01f}, {1.6f, -1, -0.01f}, {1.6f, 1, -0.01f}, {-1.6f, 1, -0.01f})); sheet.material.color = {1, 1, 1}; sheet.material.phong = {1, 0, 0, 1}; // no shading: a flat white sheet // The parameters of the demo. The keys of the demo (keyboard_event below) and the buttons of the // slide go through the same parameters and actions. slide::param("color", parameters.color, {{"black", "Black"}, {"red", "Red"}, {"blue", "Blue"}}); slide::param("width", parameters.width, 0.005f, 0.1f, 0.005f).with_label("width"); slide::param("draw", parameters.draw).with_label("Draw (else: turn the camera)"); slide::param("gui", parameters.gui).with_label("ImGui"); slide::action("undo", [this] { undo(); }).with_label("Undo"); slide::action("clear", [this] { clear(); }).with_label("Clear"); slide::readout("strokes", [this] { return float(strokes.size()); }).with_label("strokes"); // ?sample=1 starts with a stroke already drawn (a spiral): the image of the demo in a PDF if (slide::has_arg("sample")) { stroke_structure stroke; stroke.color = {0.05f, 0.05f, 0.05f}; stroke.width = 0.04f; for (int k = 0; k <= 200; ++k) { float const a = 0.1f * k, r = 0.004f * k; stroke.points.push_back({r * std::cos(a), r * std::sin(a), 0}); } update_ribbon(stroke); strokes.push_back(stroke); } } void scene_structure::display_frame() { environment.camera_view = camera_control.camera().matrix_view(); environment.light = camera_control.camera_model.position(); draw(sheet, environment); for (stroke_structure const& stroke : strokes) if (stroke.points.size() > 1) draw(stroke.ribbon, environment); } // The point under the mouse, in the plane through the origin that faces the camera: the strokes are drawn // in this plane (on the sheet as long as the camera is not turned) vec3 scene_structure::mouse_position_3d() const { intersection_structure const I = picking_plane_orthogonal_to_camera( inputs.mouse.position.current, {0, 0, 0}, camera_control.camera_model, camera_projection); return I.position; } // The ribbon of a stroke: two vertices per point, on each side of the stroke, in the plane facing the camera. // The whole mesh is rebuilt at each new point: simple, and fast enough for strokes of a few hundred points // (for longer ones, update the buffers in place, as the surface of example c3) void scene_structure::update_ribbon(stroke_structure& stroke) { size_t const N = stroke.points.size(); if (N < 2) return; vec3 const front = camera_control.camera_model.front(); mesh m; for (size_t k = 0; k < N; ++k) { vec3 const a = stroke.points[k > 0 ? k - 1 : 0]; vec3 const b = stroke.points[k + 1 < N ? k + 1 : N - 1]; vec3 side = cross(b - a, front); side = norm(side) > 1e-6f ? normalize(side) : vec3{0, 1, 0}; m.position.push_back(stroke.points[k] - 0.5f * stroke.width * side); m.position.push_back(stroke.points[k] + 0.5f * stroke.width * side); if (k + 1 < N) { unsigned int const i = static_cast<unsigned int>(2 * k); m.connectivity.push_back({i, i + 1, i + 2}); m.connectivity.push_back({i + 1, i + 3, i + 2}); } } m.fill_empty_field(); stroke.ribbon.clear(); stroke.ribbon.initialize_data_on_gpu(m); stroke.ribbon.material.color = stroke.color; stroke.ribbon.material.phong = {1, 0, 0, 1}; stroke.ribbon.material.texture_settings.two_sided = true; } void scene_structure::undo() { drawing = false; // Z during a drag: the rest of the drag draws nothing if (strokes.empty()) return; strokes.back().ribbon.clear(); // free the GPU buffers strokes.pop_back(); slide::notify(); // the number of strokes changed: the page and the slide show it } void scene_structure::clear() { drawing = false; for (stroke_structure& stroke : strokes) stroke.ribbon.clear(); strokes.clear(); slide::notify(); } void scene_structure::display_gui() { // The ImGui window of the template, hidden in a slide unless gui=1 (see example c3) ImGui::GetStyle().Alpha = parameters.gui ? 1.0f : 0.0f; if (!parameters.gui) { ImGui::SetWindowCollapsed(true); ImGui::SetWindowPos(ImVec2(-10000, -10000)); return; } ImGui::SetWindowCollapsed(false); ImGui::SetWindowPos(ImVec2(10, 10)); ImGui::Checkbox("draw", ¶meters.draw); ImGui::SliderFloat("width", ¶meters.width, 0.005f, 0.1f); if (ImGui::Button("undo")) undo(); if (ImGui::Button("clear")) clear(); } void scene_structure::mouse_move_event() { if (parameters.draw) { // extend the current stroke while the left button is down if (drawing && inputs.mouse.click.left && !strokes.empty()) { stroke_structure& stroke = strokes.back(); vec3 const p = mouse_position_3d(); if (stroke.points.empty() || norm(p - stroke.points.back()) > 0.005f) { stroke.points.push_back(p); update_ribbon(stroke); } } } else if (!inputs.keyboard.shift) camera_control.action_mouse_move(); } void scene_structure::mouse_click_event() { if (parameters.draw && !inputs.mouse.on_gui && inputs.mouse.click.last_action == last_mouse_cursor_action::click_left) { // a new stroke, with the current color and width vec3 const colors[] = {{0.05f, 0.05f, 0.05f}, {0.85f, 0.1f, 0.1f}, {0.1f, 0.3f, 0.9f}}; stroke_structure stroke; stroke.color = parameters.color == "red" ? colors[1] : parameters.color == "blue" ? colors[2] : colors[0]; stroke.width = parameters.width; stroke.points.push_back(mouse_position_3d()); strokes.push_back(stroke); drawing = true; slide::notify(); } else if (parameters.draw && inputs.mouse.click.last_action == last_mouse_cursor_action::release_left) { // a click without a move leaves a stroke of a single point: remove it if (drawing && !strokes.empty() && strokes.back().points.size() < 2) { strokes.pop_back(); slide::notify(); } drawing = false; } else camera_control.action_mouse_click(); } // The keys of the demo: letters and digits only. The arrow keys and Page Down / Page Up are sent to the // slides by the page of the demo (slide-frame.html): keep them for the presentation. void scene_structure::keyboard_event() { // No camera_control.action_keyboard() here, unlike the other examples: the keys belong to the drawing // The GLFW codes of the keys (GLFW_KEY_Z...): the names of the keys are not known on the web auto const& key = inputs.keyboard.last_action; if (key.action != GLFW_PRESS) return; if (key.key == GLFW_KEY_Z) slide::set("undo", ""); else if (key.key == GLFW_KEY_C) slide::set("clear", ""); else if (key.key == GLFW_KEY_D) slide::set("draw", parameters.draw ? "0" : "1"); else if (key.key == GLFW_KEY_1) slide::set("color", "black"); else if (key.key == GLFW_KEY_2) slide::set("color", "red"); else if (key.key == GLFW_KEY_3) slide::set("color", "blue"); else return; // a value changed from the program: the panel and the slide show it (undo and clear already notify, // this call is needed for color and draw) slide::notify(); } void scene_structure::idle_frame() { camera_control.idle_frame(); }
src/scene.hpp
Afficher le fichier complet : scene.hpp (57 lignes)
#pragma once #include "cgp/cgp.hpp" #include "environment.hpp" #include <string> #include <vector> using cgp::mesh; using cgp::mesh_drawable; using cgp::vec3; // A stroke: the points given by the mouse, and a ribbon drawn along them. WebGL draws lines one pixel // wide, too thin on a projector: the ribbon is a mesh, as wide as wanted. struct stroke_structure { std::vector<vec3> points; vec3 color; float width = 0.03f; mesh_drawable ribbon; }; // The parameters of the demo, declared to the bridge in initialize() struct sketch_parameters { std::string color = "black"; // the color of the next strokes: black, red, blue float width = 0.03f; // the width of the next strokes bool draw = true; // true: the mouse draws; false: it turns the camera bool gui = false; // the ImGui window of the template (hidden in a slide) }; struct scene_structure : cgp::scene_inputs_generic { void initialize(); void display_frame(); void display_gui(); environment_structure environment; window_structure window; input_devices inputs; camera_controller_orbit_euler camera_control; camera_projection_perspective camera_projection; mesh_drawable sheet; // the white sheet behind the strokes std::vector<stroke_structure> strokes; sketch_parameters parameters; bool drawing = false; // true while the left button draws the last stroke vec3 mouse_position_3d() const; void update_ribbon(stroke_structure& stroke); void undo(); void clear(); void mouse_move_event(); void mouse_click_event(); void keyboard_event(); void idle_frame(); };
slides.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Sketch with the mouse</title> <!-- A slide of reveal.js with the demo of this example. Open it through a web server, from the root of the repository: python3 -m http.server 8080, then http://localhost:8080/examples/c8-cgp-sketch/slides.html reveal.js comes from a CDN: for a talk without network, download it next to this file. --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/theme/white.css"> <style> .reveal iframe.demo { width: 100%; height: 540px; border: 0; } .reveal .row { font-size: 0.6em; margin-top: 12px; } .reveal .row button { font: inherit; padding: 4px 14px; margin: 0 4px; border-radius: 8px; border: 2px solid #999; background: white; cursor: pointer; } .reveal .row button.on { background: #333; color: white; border-color: #333; } </style> </head> <body> <div class="reveal"><div class="slides"> <section> <h3>Sketch with the mouse</h3> <iframe class="demo" id="demo" data-src="web/index.html?controls=width,draw&panel=br"></iframe> <div class="row"> <button data-demo-set="color=black">Black</button> <button data-demo-set="color=red">Red</button> <button data-demo-set="color=blue">Blue</button> <button data-demo-set="undo">Undo</button> <button data-demo-set="clear">Clear</button> Strokes: <span data-demo-value="strokes"></span> </div> <p style="font-size: 0.5em">Keys of the demo: Z undo, C clear, 1 2 3 colors, D draw or turn the camera. The arrow keys still change the slide.</p> </section> </div></div> <script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.js"></script> <script src="../../bridge/slide-controls.js"></script> <script>Reveal.initialize({hash: true});</script> </body> </html>
lhtml-site/
La même slide en lhtml-site (l'ouvrir), organisée comme dans
l'exemple 1 ; seule la slide change, src/01_sketch/index.html.j2 :
{% set layout = 'side' %}
= Sketch with the mouse
* Draw in the frame with the mouse
* Keys of the demo: Z undo, C clear, 1 2 3 colors, D draw or turn the camera
* The arrow keys still change the slide
<div class="controls">
<p>
<button data-demo-set="color=black">Black</button>
<button data-demo-set="color=red">Red</button>
<button data-demo-set="color=blue">Blue</button>
<button data-demo-set="undo">Undo</button>
<button data-demo-set="clear">Clear</button>
</p>
<p>Strokes: <span class="value" data-demo-value="strokes"></span></p>
</div>
media::
demo::../_demo/index.html?controls=width,draw&panel=br(.live)
img::../_demo/poster.png(.still)
::
Ensuite : 9. Deux démos côte à côte.