diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..6b20e91 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1,6 @@ +*.bin +*.idb +*.log +*.obj +*.pdb +*.tlog \ No newline at end of file diff --git a/linux/LICENSE b/linux/LICENSE new file mode 100644 index 0000000..718b616 --- /dev/null +++ b/linux/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 HackerPoet + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/linux/LICENSE-FONT.txt b/linux/LICENSE-FONT.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/linux/LICENSE-FONT.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/linux/LinuxAudio.cpp b/linux/LinuxAudio.cpp new file mode 100644 index 0000000..00e6b06 --- /dev/null +++ b/linux/LinuxAudio.cpp @@ -0,0 +1,58 @@ +#include "LinuxAudio.h" +#include +#include + +struct WinAudio::Impl { + class Stream : public sf::SoundStream { + public: + Stream(WinAudio* parent, unsigned int sampleRate) + : m_parent(parent) { + std::vector channelMap = { + sf::SoundChannel::FrontLeft, + sf::SoundChannel::FrontRight + }; + initialize(2, sampleRate, channelMap); + } + + bool onGetData(sf::SoundStream::Chunk& chunk) override { + WinAudio::Chunk c; + c.samples = m_parent->m_samples; + c.sampleCount = WinAudio::AUDIO_BUFF_SIZE; + if (!m_parent->onGetData(c)) + return false; + + chunk.samples = c.samples; + chunk.sampleCount = c.sampleCount; + return true; + } + + void onSeek(sf::Time) override {} + + private: + WinAudio* m_parent; + }; + + Impl(WinAudio* parent, int sampleRate) + : stream(parent, static_cast(sampleRate)) {} + + Stream stream; +}; + +WinAudio::WinAudio(int sample_rate) { + impl = std::make_unique(this, sample_rate); + std::memset(m_samples, 0, sizeof(m_samples)); +} + +WinAudio::~WinAudio() { + stop(); +} + +bool WinAudio::play() { + impl->stream.play(); + return true; +} + +bool WinAudio::stop() { + impl->stream.stop(); + return true; +} diff --git a/linux/LinuxAudio.h b/linux/LinuxAudio.h new file mode 100644 index 0000000..03a61c7 --- /dev/null +++ b/linux/LinuxAudio.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include + +class WinAudio { +public: + static constexpr int AUDIO_BUFF_SIZE = 4096; + + struct Chunk { + int16_t* samples = nullptr; + std::size_t sampleCount = 0; + }; + + explicit WinAudio(int sample_rate); + virtual ~WinAudio(); + + virtual bool onGetData(Chunk& data) = 0; + + bool play(); + bool stop(); + +protected: + int16_t m_samples[AUDIO_BUFF_SIZE]; + +private: + struct Impl; + std::unique_ptr impl; +}; diff --git a/linux/LinuxAudio.o b/linux/LinuxAudio.o new file mode 100644 index 0000000..437a52e Binary files /dev/null and b/linux/LinuxAudio.o differ diff --git a/linux/Main.cpp b/linux/Main.cpp new file mode 100644 index 0000000..d3da395 --- /dev/null +++ b/linux/Main.cpp @@ -0,0 +1,597 @@ +#define _USE_MATH_DEFINES +#define _CRT_SECURE_NO_WARNINGS +#include "LinuxAudio.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const int target_fps = 60; +static const int sample_rate = 48000; +static const int max_freq = 4000; +static const int window_w_init = 1280; +static const int window_h_init = 720; +static const int starting_fractal = 0; +static const int max_iters = 1200; +static const double escape_radius_sq = 1000.0; +static const char window_name[] = "Fractal Sound Explorer"; + +static int window_w = window_w_init; +static int window_h = window_h_init; +static double cam_x = 0.0; +static double cam_y = 0.0; +static double cam_zoom = 100.0; +static int cam_x_fp = 0; +static int cam_y_fp = 0; +static double cam_x_dest = cam_x; +static double cam_y_dest = cam_y; +static double cam_zoom_dest = cam_zoom; +static bool sustain = true; +static bool normalized = true; +static bool use_color = false; +static bool hide_orbit = true; +static double jx = 1e8; +static double jy = 1e8; +static int frame = 0; + +typedef void (*Fractal)(double&, double&, double, double); +static Fractal fractal = nullptr; + +const sf::BlendMode BlendAlpha = sf::BlendAlpha; +const sf::BlendMode BlendIgnoreAlpha = sf::BlendNone; + +void ScreenToPt(int x, int y, double& px, double& py) { + px = double(x - window_w / 2) / cam_zoom - cam_x; + py = double(y - window_h / 2) / cam_zoom - cam_y; +} + +void PtToScreen(double px, double py, int& x, int& y) { + x = int(cam_zoom * (px + cam_x)) + window_w / 2; + y = int(cam_zoom * (py + cam_y)) + window_h / 2; +} + +void mandelbrot(double& x, double& y, double cx, double cy) { + double nx = x * x - y * y + cx; + double ny = 2.0 * x * y + cy; + x = nx; + y = ny; +} + +void burning_ship(double& x, double& y, double cx, double cy) { + double nx = x * x - y * y + cx; + double ny = 2.0 * std::abs(x * y) + cy; + x = nx; + y = ny; +} + +void feather(double& x, double& y, double cx, double cy) { + std::complex z(x, y); + std::complex z2(x * x, y * y); + std::complex c(cx, cy); + std::complex one(1.0, 0.0); + z = z * z * z / (one + z2) + c; + x = z.real(); + y = z.imag(); +} + +void sfx(double& x, double& y, double cx, double cy) { + std::complex z(x, y); + std::complex c2(cx * cx, cy * cy); + z = z * (x * x + y * y) - (z * c2); + x = z.real(); + y = z.imag(); +} + +void henon(double& x, double& y, double cx, double cy) { + double nx = 1.0 - cx * x * x + y; + double ny = cy * x; + x = nx; + y = ny; +} + +void duffing(double& x, double& y, double cx, double cy) { + double nx = y; + double ny = -cy * x + cx * y - y * y * y; + x = nx; + y = ny; +} + +void ikeda(double& x, double& y, double cx, double cy) { + double t = 0.4 - 6.0 / (1.0 + x * x + y * y); + double st = std::sin(t); + double ct = std::cos(t); + double nx = 1.0 + cx * (x * ct - y * st); + double ny = cy * (x * st + y * ct); + x = nx; + y = ny; +} + +void chirikov(double& x, double& y, double cx, double cy) { + y += cy * std::sin(x); + x += cx * y; +} + +static const Fractal all_fractals[] = { + mandelbrot, + burning_ship, + feather, + sfx, + henon, + duffing, + ikeda, + chirikov, +}; + +class Synth : public WinAudio { +public: + bool audio_reset; + bool audio_pause; + double volume; + double play_x, play_y; + double play_cx, play_cy; + double play_nx, play_ny; + double play_px, play_py; + + Synth() : WinAudio(sample_rate) { + audio_reset = true; + audio_pause = false; + volume = 8000.0; + play_x = 0.0; + play_y = 0.0; + play_cx = 0.0; + play_cy = 0.0; + play_nx = 0.0; + play_ny = 0.0; + play_px = 0.0; + play_py = 0.0; + } + + void SetPoint(double x, double y) { + play_nx = x; + play_ny = y; + audio_reset = true; + audio_pause = false; + } + + virtual bool onGetData(Chunk& data) override { + data.samples = m_samples; + data.sampleCount = AUDIO_BUFF_SIZE; + std::memset(m_samples, 0, sizeof(m_samples)); + + if (audio_reset) { + m_audio_time = 0; + play_cx = (jx < 1e8 ? jx : play_nx); + play_cy = (jy < 1e8 ? jy : play_ny); + play_x = play_nx; + play_y = play_ny; + play_px = play_nx; + play_py = play_ny; + mean_x = play_nx; + mean_y = play_ny; + volume = 8000.0; + audio_reset = false; + } + + if (audio_pause) { + return true; + } + + const int steps = sample_rate / max_freq; + for (int i = 0; i < AUDIO_BUFF_SIZE; i += 2) { + const int j = m_audio_time % steps; + if (j == 0) { + play_px = play_x; + play_py = play_y; + fractal(play_x, play_y, play_cx, play_cy); + if (play_x * play_x + play_y * play_y > escape_radius_sq) { + audio_pause = true; + return true; + } + + if (normalized) { + dpx = play_px - play_cx; + dpy = play_py - play_cy; + dx = play_x - play_cx; + dy = play_y - play_cy; + if (dx != 0.0 || dy != 0.0) { + double dpmag = 1.0 / std::sqrt(1e-12 + dpx * dpx + dpy * dpy); + double dmag = 1.0 / std::sqrt(1e-12 + dx * dx + dy * dy); + dpx *= dpmag; + dpy *= dpmag; + dx *= dmag; + dy *= dmag; + } + } else { + dx = play_x - mean_x; + dy = play_y - mean_y; + dpx = play_px - mean_x; + dpy = play_py - mean_y; + } + + mean_x = mean_x * 0.99 + play_x * 0.01; + mean_y = mean_y * 0.99 + play_y * 0.01; + + double m = dx * dx + dy * dy; + if (m > 2.0) { + dx *= 2.0 / m; + dy *= 2.0 / m; + } + m = dpx * dpx + dpy * dpy; + if (m > 2.0) { + dpx *= 2.0 / m; + dpy *= 2.0 / m; + } + + if (!sustain) { + volume *= 0.9992; + } + } + + double t = double(j) / double(steps); + t = 0.5 - 0.5 * std::cos(t * 3.14159); + double wx = t * dx + (1.0 - t) * dpx; + double wy = t * dy + (1.0 - t) * dpy; + + m_samples[i] = (int16_t)std::min(std::max(wx * volume, -32000.0), 32000.0); + m_samples[i + 1] = (int16_t)std::min(std::max(wy * volume, -32000.0), 32000.0); + m_audio_time += 1; + } + + return !audio_reset; + } + + int16_t m_samples[AUDIO_BUFF_SIZE]; + int32_t m_audio_time; + double mean_x; + double mean_y; + double dx; + double dy; + double dpx; + double dpy; +}; + +void SetFractal(sf::Shader& shader, int type, Synth& synth) { + shader.setUniform("iType", type); + jx = jy = 1e8; + fractal = all_fractals[type]; + normalized = (type == 0); + synth.audio_pause = true; + hide_orbit = true; + frame = 0; +} + +void resize_window(sf::RenderWindow& window, sf::RenderTexture& rt, const sf::ContextSettings&, int w, int h) { + window_w = w; + window_h = h; + rt = sf::RenderTexture(sf::Vector2u((unsigned)w, (unsigned)h)); + window.setView(sf::View(sf::FloatRect(sf::Vector2f(0.f, 0.f), sf::Vector2f((float)w, (float)h)))); + frame = 0; +} + +void make_window(sf::RenderWindow& window, sf::RenderTexture& rt, const sf::ContextSettings& settings, bool is_fullscreen) { + window.close(); + sf::VideoMode screenSize; + if (is_fullscreen) { + screenSize = sf::VideoMode::getDesktopMode(); + window.create(screenSize, window_name, sf::State::Fullscreen, settings); + } else { + screenSize = sf::VideoMode(sf::Vector2u(window_w_init, window_h_init), 24); + window.create(screenSize, window_name, sf::State::Windowed, settings); + } + resize_window(window, rt, settings, (int)screenSize.size.x, (int)screenSize.size.y); + window.setFramerateLimit(target_fps); + window.setKeyRepeatEnabled(false); + window.requestFocus(); +} + +#if _WIN32 +INT WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) { +#else +int main(int argc, char *argv[]) { +#endif + if (!sf::Shader::isAvailable()) { + std::cerr << "Graphics card does not support shaders" << std::endl; + return 1; + } + + sf::Shader shader; + if (!shader.loadFromFile("vert.glsl", sf::Shader::Type::Vertex)) { + std::cerr << "Failed to compile vertex shader" << std::endl; + return 1; + } + if (!shader.loadFromFile("frag.glsl", sf::Shader::Type::Fragment)) { + std::cerr << "Failed to compile fragment shader" << std::endl; + return 1; + } + + sf::Font font; + if (!font.openFromFile("RobotoMono-Medium.ttf")) { + std::cerr << "Failed to load font" << std::endl; + return 1; + } + + sf::RectangleShape rect; + rect.setPosition(sf::Vector2f(0.f, 0.f)); + + sf::ContextSettings settings; + settings.depthBits = 24; + settings.stencilBits = 8; + settings.antiAliasingLevel = 4; + settings.majorVersion = 3; + settings.minorVersion = 0; + + sf::RenderWindow window; + sf::RenderTexture renderTexture; + bool is_fullscreen = false; + bool toggle_fullscreen = false; + make_window(window, renderTexture, settings, is_fullscreen); + + Synth synth{}; + + shader.setUniform("iCam", sf::Vector2f((float)cam_x, (float)cam_y)); + shader.setUniform("iZoom", (float)cam_zoom); + SetFractal(shader, starting_fractal, synth); + synth.play(); + + double px = 0.0, py = 0.0, orbit_x = 0.0, orbit_y = 0.0; + bool leftPressed = false; + bool dragging = false; + bool juliaDrag = false; + bool takeScreenshot = false; + bool showHelpMenu = false; + sf::Vector2i prevDrag; + + while (window.isOpen()) { + while (auto eventOpt = window.pollEvent()) { + const auto& event = *eventOpt; + + if (event.is()) { + window.close(); + break; + } else if (event.is()) { + auto resized = event.getIf(); + if (resized) { + resize_window(window, renderTexture, settings, (int)resized->size.x, (int)resized->size.y); + } + } else if (event.is()) { + auto keyEvent = event.getIf(); + if (keyEvent) { + const sf::Keyboard::Key keycode = keyEvent->code; + if (keycode == sf::Keyboard::Key::Escape) { + window.close(); + break; + } else if (keycode >= sf::Keyboard::Key::Num1 && keycode <= sf::Keyboard::Key::Num8) { + SetFractal(shader, int(keycode) - int(sf::Keyboard::Key::Num1), synth); + } else if (keycode == sf::Keyboard::Key::F11) { + toggle_fullscreen = true; + } else if (keycode == sf::Keyboard::Key::D) { + sustain = !sustain; + } else if (keycode == sf::Keyboard::Key::C) { + use_color = !use_color; + frame = 0; + } else if (keycode == sf::Keyboard::Key::R) { + cam_x = cam_x_dest = 0.0; + cam_y = cam_y_dest = 0.0; + cam_zoom = cam_zoom_dest = 100.0; + frame = 0; + } else if (keycode == sf::Keyboard::Key::J) { + if (jx < 1e8) { + jx = jy = 1e8; + } else { + juliaDrag = true; + const sf::Vector2i mousePos = sf::Mouse::getPosition(window); + ScreenToPt(mousePos.x, mousePos.y, jx, jy); + } + synth.audio_pause = true; + hide_orbit = true; + frame = 0; + } else if (keycode == sf::Keyboard::Key::S) { + takeScreenshot = true; + } else if (keycode == sf::Keyboard::Key::H) { + showHelpMenu = !showHelpMenu; + } + } + } else if (event.is()) { + auto keyEvent = event.getIf(); + if (keyEvent && keyEvent->code == sf::Keyboard::Key::J) { + juliaDrag = false; + frame = 0; + } + } else if (event.is()) { + auto wheel = event.getIf(); + if (wheel) { + cam_zoom_dest *= std::pow(1.1f, wheel->delta); + const sf::Vector2i mouse_pos = sf::Mouse::getPosition(window); + cam_x_fp = mouse_pos.x; + cam_y_fp = mouse_pos.y; + } + } else if (event.is()) { + auto mouse = event.getIf(); + if (mouse) { + if (mouse->button == sf::Mouse::Button::Left) { + leftPressed = true; + hide_orbit = false; + ScreenToPt(mouse->position.x, mouse->position.y, px, py); + synth.SetPoint(px, py); + orbit_x = px; + orbit_y = py; + } else if (mouse->button == sf::Mouse::Button::Middle) { + prevDrag = sf::Vector2i(mouse->position.x, mouse->position.y); + dragging = true; + } else if (mouse->button == sf::Mouse::Button::Right) { + synth.audio_pause = true; + hide_orbit = true; + } + } + } else if (event.is()) { + auto mouse = event.getIf(); + if (mouse) { + if (mouse->button == sf::Mouse::Button::Left) { + leftPressed = false; + } else if (mouse->button == sf::Mouse::Button::Middle) { + dragging = false; + } + } + } else if (event.is()) { + auto move = event.getIf(); + if (move) { + if (leftPressed) { + ScreenToPt(move->position.x, move->position.y, px, py); + synth.SetPoint(px, py); + orbit_x = px; + orbit_y = py; + } + if (dragging) { + sf::Vector2i curDrag = sf::Vector2i(move->position.x, move->position.y); + cam_x_dest += (curDrag.x - prevDrag.x) / cam_zoom; + cam_y_dest += (curDrag.y - prevDrag.y) / cam_zoom; + prevDrag = curDrag; + frame = 0; + } + if (juliaDrag) { + ScreenToPt(move->position.x, move->position.y, jx, jy); + frame = 0; + } + } + } + } + + double fpx, fpy, delta_cam_x, delta_cam_y; + + // World coords at zoom focus before zoom + ScreenToPt(cam_x_fp, cam_y_fp, fpx, fpy); + + // Smooth zoom toward target + cam_zoom = cam_zoom * 0.9 + cam_zoom_dest * 0.1; + + // World coords at zoom focus after zoom + ScreenToPt(cam_x_fp, cam_y_fp, delta_cam_x, delta_cam_y); + + // Adjust destination so the zoom focus stays roughly under the cursor + cam_x_dest += delta_cam_x - fpx; + cam_y_dest += delta_cam_y - fpy; + + // Smooth camera position toward destination + cam_x = cam_x * 0.9 + cam_x_dest * 0.1; + cam_y = cam_y * 0.9 + cam_y_dest * 0.1; + + const bool hasJulia = (jx < 1e8); + const bool drawMset = (juliaDrag || !hasJulia); + const bool drawJset = (juliaDrag || hasJulia); + const int flags = (drawMset ? 0x01 : 0) | (drawJset ? 0x02 : 0) | (use_color ? 0x04 : 0); + + const sf::Glsl::Vec2 window_res((float)window_w, (float)window_h); + shader.setUniform("iResolution", window_res); + shader.setUniform("iCam", sf::Vector2f((float)cam_x, (float)cam_y)); + shader.setUniform("iZoom", (float)cam_zoom); + shader.setUniform("iFlags", flags); + shader.setUniform("iJulia", sf::Vector2f((float)jx, (float)jy)); + shader.setUniform("iIters", max_iters); + shader.setUniform("iTime", frame); + + sf::RenderStates states = sf::RenderStates::Default; + states.blendMode = (frame > 0 ? BlendAlpha : BlendIgnoreAlpha); + states.shader = &shader; + rect.setSize(window_res); + renderTexture.clear(sf::Color::Transparent); + renderTexture.draw(rect, states); + renderTexture.display(); + + sf::Sprite sprite(renderTexture.getTexture()); + window.clear(); + window.draw(sprite, sf::RenderStates(BlendIgnoreAlpha)); + + if (takeScreenshot) { + window.display(); + const time_t t = std::time(0); + const tm* now = std::localtime(&t); + char buffer[128]; + std::strftime(buffer, sizeof(buffer), "pic_%m-%d-%y_%H-%M-%S.png", now); + sf::Texture texture; + texture = sf::Texture(sf::Vector2u(window.getSize())); + texture.update(window); + texture.copyToImage().saveToFile(buffer); + takeScreenshot = false; + } + + if (!hide_orbit) { + glLineWidth(1.0f); + glColor3f(1.0f, 0.0f, 0.0f); + glBegin(GL_LINE_STRIP); + int sx, sy; + double x = orbit_x; + double y = orbit_y; + PtToScreen(x, y, sx, sy); + glVertex2i(sx, sy); + double cx = (hasJulia ? jx : px); + double cy = (hasJulia ? jy : py); + for (int i = 0; i < 200; ++i) { + fractal(x, y, cx, cy); + PtToScreen(x, y, sx, sy); + glVertex2i(sx, sy); + if (x * x + y * y > escape_radius_sq) { + break; + } else if (i < max_freq / target_fps) { + orbit_x = x; + orbit_y = y; + } + } + glEnd(); + } + + if (showHelpMenu) { + sf::RectangleShape dimRect(sf::Vector2f((float)window_w, (float)window_h)); + dimRect.setFillColor(sf::Color(0, 0, 0, 128)); + window.draw(dimRect, sf::RenderStates(BlendAlpha)); + + sf::Text helpMenu(font, "", 24); + helpMenu.setFillColor(sf::Color::White); + helpMenu.setString( + " H - Toggle Help Menu Left Mouse - Click or drag to hear orbits\n" + " D - Toggle Audio Dampening Middle Mouse - Drag to pan view\n" + " C - Toggle Color Right Mouse - Stop orbit and sound\n" + "F11 - Toggle Fullscreen Scroll Wheel - Zoom in and out\n" + " S - Save Snapshot\n" + " R - Reset View\n" + " J - Hold down, move mouse, and\n" + " release to make Julia sets.\n" + " Press again to switch back.\n" + " 1 - Mandelbrot Set\n" + " 2 - Burning Ship\n" + " 3 - Feather Fractal\n" + " 4 - SFX Fractal\n" + " 5 - Hénon Map\n" + " 6 - Duffing Map\n" + " 7 - Ikeda Map\n" + " 8 - Chirikov Map\n" + ); + helpMenu.setPosition(sf::Vector2f(20.f, 20.f)); + window.draw(helpMenu); + } + + window.display(); + + const double xSpeed = std::abs(cam_x - cam_x_dest) * cam_zoom_dest; + const double ySpeed = std::abs(cam_y - cam_y_dest) * cam_zoom_dest; + const double zoomSpeed = std::abs(cam_zoom / cam_zoom_dest - 1.0); + if (xSpeed < 0.2 && ySpeed < 0.2 && zoomSpeed < 0.002) { + frame += 1; + } else { + frame = 1; + } + + if (toggle_fullscreen) { + toggle_fullscreen = false; + is_fullscreen = !is_fullscreen; + make_window(window, renderTexture, settings, is_fullscreen); + } + } + + synth.stop(); + return 0; +} diff --git a/linux/Main.o b/linux/Main.o new file mode 100644 index 0000000..639d7ab Binary files /dev/null and b/linux/Main.o differ diff --git a/linux/Makefile b/linux/Makefile new file mode 100644 index 0000000..c8b587c --- /dev/null +++ b/linux/Makefile @@ -0,0 +1,19 @@ +CXX=g++ +CXXFLAGS=-std=c++17 -O2 -Wall $(shell pkg-config --cflags sfml-graphics sfml-window sfml-system sfml-audio) +LDFLAGS=$(shell pkg-config --libs sfml-graphics sfml-window sfml-system sfml-audio) -lGL +SRCS=$(wildcard *.cpp) +OBJS=$(SRCS:.cpp=.o) +TARGET=fractal + +all: $(TARGET) + +$(TARGET): $(OBJS) + $(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS) + +%.o: %.cpp + $(CXX) $(CXXFLAGS) -c $< -o $@ + +clean: + rm -f $(OBJS) $(TARGET) + +.PHONY: all clean diff --git a/linux/MandelbrotMusic.vcxproj b/linux/MandelbrotMusic.vcxproj new file mode 100644 index 0000000..581158e --- /dev/null +++ b/linux/MandelbrotMusic.vcxproj @@ -0,0 +1,140 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {22F2085E-A7FC-448F-B674-172B2D20AE70} + Clusters + 8.1 + MandelbrotSound + + + + Application + true + v140 + MultiByte + + + Application + false + v140 + true + MultiByte + + + Application + true + v140 + MultiByte + + + Application + false + v140 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + + + + + Level3 + Disabled + true + C:\Program Files\SFML\include + SFML_STATIC;%(PreprocessorDefinitions) + MultiThreadedDebug + + + C:\Program Files\SFML\lib;%(AdditionalLibraryDirectories) + sfml-graphics-s-d.lib;sfml-system-s-d.lib;sfml-window-s-d.lib;opengl32.lib;winmm.lib;gdi32.lib;glu32.lib;freetype.lib;%(AdditionalDependencies) + Windows + + + + + Level3 + MaxSpeed + true + true + true + + + true + true + + + + + Level3 + MaxSpeed + true + true + true + C:\Program Files\SFML\include + SFML_STATIC;%(PreprocessorDefinitions) + MultiThreaded + + + true + true + C:\Program Files\SFML\lib;%(AdditionalLibraryDirectories) + sfml-graphics-s.lib;sfml-system-s.lib;sfml-window-s.lib;opengl32.lib;winmm.lib;gdi32.lib;glu32.lib;freetype.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/linux/MandelbrotMusic.vcxproj.filters b/linux/MandelbrotMusic.vcxproj.filters new file mode 100644 index 0000000..193eba9 --- /dev/null +++ b/linux/MandelbrotMusic.vcxproj.filters @@ -0,0 +1,38 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + + + Header Files + + + \ No newline at end of file diff --git a/linux/MandelbrotMusic.vcxproj.user b/linux/MandelbrotMusic.vcxproj.user new file mode 100644 index 0000000..abe8dd8 --- /dev/null +++ b/linux/MandelbrotMusic.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/linux/README.md b/linux/README.md new file mode 100644 index 0000000..3cc4a17 --- /dev/null +++ b/linux/README.md @@ -0,0 +1,36 @@ +# Fractal Sound Explorer +Explore fractals in an audio-visual sandbox + +Download executable on my itch.io page: +https://codeparade.itch.io/fractal-sound-explorer + +YouTube video explanation: +https://youtu.be/GiAj9WW1OfQ + +![](https://img.itch.zone/aW1hZ2UvOTM1NzMzLzUzMTU0MzEucG5n/original/ay7ju0.png) + +Notes +--------------- +The fractals are designed to run in real time on a GPU. If the program is going too slow, you can simply shrink the size of the window to make it run faster. The rendering is also designed to increase the image quality over time. So keep still for a bit before taking screenshots to get higher quality. + +Controls +--------------- +* H - Toggle Help Menu +* Left Mouse - Click or drag to hear orbits +* Middle Mouse - Drag to pan view +* Right Mouse - Stop orbit and sound +* Scroll Wheel - Zoom in and out +* D - Toggle Audio Dampening +* C - Toggle Color +* F11 - Toggle Fullscreen +* S - Save Snapshot +* R - Reset View +* J - Hold down, move mouse, and release to make Julia sets. Press again to switch back. +* 1 - Mandelbrot Set +* 2 - Burning Ship +* 3 - Feather Fractal +* 4 - SFX Fractal +* 5 - Hénon Map +* 6 - Duffing Map +* 7 - Ikeda Map +* 8 - Chirikov Map diff --git a/linux/RobotoMono-Medium.ttf b/linux/RobotoMono-Medium.ttf new file mode 100644 index 0000000..8461be7 Binary files /dev/null and b/linux/RobotoMono-Medium.ttf differ diff --git a/linux/fractal b/linux/fractal new file mode 100644 index 0000000..10e16ba Binary files /dev/null and b/linux/fractal differ diff --git a/linux/frag.glsl b/linux/frag.glsl new file mode 100644 index 0000000..034f118 --- /dev/null +++ b/linux/frag.glsl @@ -0,0 +1,160 @@ +#version 400 compatibility +#extension GL_ARB_gpu_shader_fp64 : enable +// #pragma optionNV(fastmath off) +// #pragma optionNV(fastprecision off) + +#define FLOAT float +#define VEC2 vec2 +#define VEC3 vec3 +#define AA_LEVEL 1 +#define ESCAPE 1000.0 +#define PI 3.141592653 + +#define FLAG_DRAW_MSET ((iFlags & 0x01) == 0x01) +#define FLAG_DRAW_JSET ((iFlags & 0x02) == 0x02) +#define FLAG_USE_COLOR ((iFlags & 0x04) == 0x04) + +uniform vec2 iResolution; +uniform vec2 iCam; +uniform vec2 iJulia; +uniform float iZoom; +uniform int iType; +uniform int iIters; +uniform int iFlags; +uniform int iTime; + +#define cx_one VEC2(1.0, 0.0) +VEC2 cx_mul(VEC2 a, VEC2 b) { + return VEC2(a.x*b.x - a.y*b.y, a.x*b.y + a.y*b.x); +} +VEC2 cx_sqr(VEC2 a) { + FLOAT x2 = a.x*a.x; + FLOAT y2 = a.y*a.y; + FLOAT xy = a.x*a.y; + return VEC2(x2 - y2, xy + xy); +} +VEC2 cx_cube(VEC2 a) { + FLOAT x2 = a.x*a.x; + FLOAT y2 = a.y*a.y; + FLOAT d = x2 - y2; + return VEC2(a.x*(d - y2 - y2), a.y*(x2 + x2 + d)); +} +VEC2 cx_div(VEC2 a, VEC2 b) { + FLOAT denom = 1.0 / (b.x*b.x + b.y*b.y); + return VEC2(a.x*b.x + a.y*b.y, a.y*b.x - a.x*b.y) * denom; +} +VEC2 cx_sin(VEC2 a) { + return VEC2(sin(a.x) * cosh(a.y), cos(a.x) * sinh(a.y)); +} +VEC2 cx_cos(VEC2 a) { + return VEC2(cos(a.x) * cosh(a.y), -sin(a.x) * sinh(a.y)); +} +VEC2 cx_exp(VEC2 a) { + return exp(a.x) * VEC2(cos(a.y), sin(a.y)); +} + +//Fractal equations +VEC2 mandelbrot(VEC2 z, VEC2 c) { + return cx_sqr(z) + c; +} +VEC2 burning_ship(VEC2 z, VEC2 c) { + return VEC2(z.x*z.x - z.y*z.y, 2.0*abs(z.x * z.y)) + c; +} +VEC2 feather(VEC2 z, VEC2 c) { + return cx_div(cx_cube(z), cx_one + z*z) + c; +} +VEC2 sfx(VEC2 z, VEC2 c) { + return z * dot(z,z) - cx_mul(z, c*c); +} +VEC2 henon(VEC2 z, VEC2 c) { + return VEC2(1.0 - c.x*z.x*z.x + z.y, c.y * z.x); +} +VEC2 duffing(VEC2 z, VEC2 c) { + return VEC2(z.y, -c.y*z.x + c.x*z.y - z.y*z.y*z.y); +} +VEC2 ikeda(VEC2 z, VEC2 c) { + FLOAT t = 0.4 - 6.0/(1.0 + dot(z,z)); + FLOAT st = sin(t); + FLOAT ct = cos(t); + return VEC2(1.0 + c.x*(z.x*ct - z.y*st), c.y*(z.x*st + z.y*ct)); +} +VEC2 chirikov(VEC2 z, VEC2 c) { + z.y += c.y*sin(z.x); + z.x += c.x*z.y; + return z; +} + +#if 1 +#define DO_LOOP(name) \ + for (i = 0; i < iIters; ++i) { \ + VEC2 ppz = pz; \ + pz = z; \ + z = name(z, c); \ + if (dot(z, z) > ESCAPE) { break; } \ + sumz.x += dot(z - pz, pz - ppz); \ + sumz.y += dot(z - pz, z - pz); \ + sumz.z += dot(z - ppz, z - ppz); \ + } +#else +#define DO_LOOP(name) \ + for (i = 0; i < iIters; ++i) { \ + z = name(z, c); \ + if (dot(z, z) > ESCAPE) { break; } \ + } +#endif + +vec3 fractal(VEC2 z, VEC2 c) { + VEC2 pz = z; + VEC3 sumz = VEC3(0.0, 0.0, 0.0); + int i; + switch (iType) { + case 0: DO_LOOP(mandelbrot); break; + case 1: DO_LOOP(burning_ship); break; + case 2: DO_LOOP(feather); break; + case 3: DO_LOOP(sfx); break; + case 4: DO_LOOP(henon); break; + case 5: DO_LOOP(duffing); break; + case 6: DO_LOOP(ikeda); break; + case 7: DO_LOOP(chirikov); break; + } + + if (i != iIters) { + float n1 = sin(float(i) * 0.1) * 0.5 + 0.5; + float n2 = cos(float(i) * 0.1) * 0.5 + 0.5; + return vec3(n1, n2, 1.0) * (1.0 - float(FLAG_USE_COLOR)*0.85); + } else if (FLAG_USE_COLOR) { + sumz = abs(sumz) / iIters; + vec3 n1 = sin(abs(sumz * 5.0)) * 0.45 + 0.5; + return n1; + } else { + return vec3(0.0, 0.0, 0.0); + } +} + +float rand(float s) { + return fract(sin(s*12.9898) * 43758.5453); +} + +void main() { + //Get normalized screen coordinate + vec2 screen_pos = gl_FragCoord.xy - (iResolution.xy * 0.5); + + vec3 col = vec3(0.0, 0.0, 0.0); + for (int i = 0; i < AA_LEVEL; ++i) { + vec2 dxy = vec2(rand(i*0.54321 + iTime), rand(i*0.12345 + iTime)); + VEC2 c = VEC2((screen_pos + dxy) * vec2(1.0, -1.0) / iZoom - iCam); + + if (FLAG_DRAW_MSET) { + col += fractal(c, c); + } + if (FLAG_DRAW_JSET) { + col += fractal(c, iJulia); + } + } + + col /= AA_LEVEL; + if (FLAG_DRAW_MSET && FLAG_DRAW_JSET) { + col *= 0.5; + } + gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0); +} \ No newline at end of file diff --git a/linux/vert.glsl b/linux/vert.glsl new file mode 100644 index 0000000..e467528 --- /dev/null +++ b/linux/vert.glsl @@ -0,0 +1,6 @@ +#version 400 compatibility +uniform vec2 iResolution; +void main() { + vec2 pos = (gl_Vertex.xy / iResolution) * 2.0 - vec2(1.0, 1.0); + gl_Position = vec4(pos, 0.0, 1.0); +}