├── LICENSE ├── README.md ├── SDL.mojo ├── cmap.mojo ├── gencmap.py └── mandelbrot.mojo /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Minimal SDL binding for Mojo 🔥 2 | Very basic native Mojo bindings to SDL2. No Python is used at runtime. 3 | A Python script to generate different colormaps for the demo is included. 4 | 5 | ## Usage 6 | Requires SDL installed: 7 | #### Ubuntu 8 | ```bash 9 | apt install libsdl2-dev 10 | ``` 11 | #### Fedora 12 | ```bash 13 | dnf install sdl2-devel 14 | ``` 15 | #### Mac OS 16 | ```bash 17 | brew install sdl2 18 | ``` 19 | 20 | 21 | Copy `SDL.mojo` to your project or try the Mandelbrot demo ported from [Mojo examples](https://github.com/modularml/mojo/tree/main/examples/mandelbrot.mojo) 22 | 23 | ## Demo 24 | Run 25 | ```bash 26 | mojo mandelbrot.mojo 27 | ``` 28 | and zoom in/out with the mouse wheel. 29 | -------------------------------------------------------------------------------- /SDL.mojo: -------------------------------------------------------------------------------- 1 | from sys import ffi, info 2 | 3 | fn get_sdl_lib_path() -> StringLiteral: 4 | if (info.os_is_linux()): 5 | var lib_path = '/usr/lib/x86_64-linux-gnu/libSDL2.so' 6 | try: 7 | with open('/etc/os-release', 'r') as f: 8 | var release = f.read() 9 | if (release.find('Ubuntu') < 0): 10 | lib_path = '/usr/lib64/libSDL2.so' 11 | except: 12 | print("Can't detect Linux version") 13 | return lib_path 14 | if (info.os_is_macos()): 15 | return '/opt/homebrew/lib/libSDL2.dylib' 16 | return "" 17 | 18 | # SDL_PIXELFORMAT_RGBA8888 = 19 | # SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_RGBA, 20 | # SDL_PACKEDLAYOUT_8888, 32, 4), 21 | 22 | alias SDL_PIXELTYPE_PACKED32 = 6 23 | alias SDL_PACKEDORDER_RGBA = 4 24 | alias SDL_PACKEDLAYOUT_8888 = 6 25 | 26 | 27 | fn SDL_DEFINE_PIXELFORMAT(type: Int, order: Int, layout: Int, bits: Int, bytes: Int) -> Int: 28 | return ((1 << 28) | ((type) << 24) | ((order) << 20) | ((layout) << 16) | ((bits) << 8) | ((bytes) << 0)) 29 | 30 | alias SDL_PIXELFORMAT_RGBA8888 = SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, 31 | SDL_PACKEDORDER_RGBA, 32 | SDL_PACKEDLAYOUT_8888, 33 | 32, 34 | 4) 35 | 36 | alias SDL_TEXTUREACCESS_TARGET = 2 37 | 38 | 39 | 40 | 41 | @register_passable('trivial') 42 | struct SDL_Window: 43 | pass 44 | 45 | @register_passable('trivial') 46 | struct SDL_Rect: 47 | var x: Int32 48 | var y: Int32 49 | var w: Int32 50 | var h: Int32 51 | 52 | @register_passable('trivial') 53 | struct SDL_PixelFormat: 54 | pass 55 | 56 | @register_passable('trivial') 57 | struct SDL_Renderer: 58 | pass 59 | 60 | @register_passable('trivial') 61 | struct SDL_Texture: 62 | pass 63 | 64 | @register_passable('trivial') 65 | struct SDL_Surface: 66 | var flags: UInt32 67 | var format: Pointer[SDL_PixelFormat] 68 | var w: Int32 69 | var h: Int32 70 | var pitch: Int32 71 | var pixels: Pointer[UInt32] 72 | var userdata: Pointer[Int8] 73 | var locked: Int32 74 | var list_blitmap: Pointer[Int8] 75 | var clip_rect: SDL_Rect 76 | var map: Pointer[Int8] 77 | var refcount: Int32 78 | 79 | 80 | 81 | alias SDL_QUIT = 0x100 82 | 83 | alias SDL_KEYDOWN = 0x300 84 | alias SDL_KEYUP = 0x301 85 | #alias SDL_ 86 | 87 | alias SDL_MOUSEMOTION = 0x400 88 | alias SDL_MOUSEBUTTONDOWN = 0x401 89 | alias SDL_MOUSEBUTTONUP = 0x402 90 | alias SDL_MOUSEWHEEL = 0x403 91 | 92 | @register_passable('trivial') 93 | struct Keysym: 94 | var scancode: Int32 95 | var keycode: Int32 96 | var mod: UInt16 97 | var unused: UInt32 98 | 99 | @register_passable('trivial') 100 | struct MouseMotionEvent: 101 | var type: UInt32 102 | var timestamp: UInt32 103 | var windowID: UInt32 104 | var which: UInt32 105 | var state: UInt32 106 | var x: Int32 107 | var y: Int32 108 | var xrel: Int32 109 | var yrel: Int32 110 | 111 | @register_passable('trivial') 112 | struct MouseButtonEvent: 113 | var type: UInt32 114 | var timestamp: UInt32 115 | var windowID: UInt32 116 | var which: UInt32 117 | var button: UInt8 118 | var state: UInt8 119 | var clicks: UInt8 120 | var padding1: UInt8 121 | var x: Int32 122 | var y: Int32 123 | 124 | @register_passable('trivial') 125 | struct MouseWheelEvent: 126 | var type: UInt32 127 | var timestamp: UInt32 128 | var windowID: UInt32 129 | var which: UInt32 130 | var x: Int32 131 | var y: Int32 132 | var direction: UInt32 133 | var preciseX: Float32 134 | var preciseY: Float32 135 | var mouseX: Int32 136 | var mouseY: Int32 137 | 138 | @register_passable('trivial') 139 | struct Event: 140 | var type: Int32 141 | var _padding: SIMD[DType.uint8, 16] 142 | var _padding2: Int64 143 | var _padding3: Int64 144 | def __init__() -> Event: 145 | return Event { type: 0, _padding: 0, _padding2: 0, _padding3: 0 } 146 | 147 | #fn __init__(inout self): 148 | # self.type = 0 149 | # self._padding = 0 150 | # self._padding2 = 0 151 | # self._padding3 = 0 152 | # self._padding4 = 0 153 | 154 | def as_keyboard(self) -> Keyevent: 155 | return Pointer.address_of(self).bitcast[Keyevent]().load() 156 | 157 | def as_mousemotion(self) -> MouseMotionEvent: 158 | return Pointer.address_of(self).bitcast[MouseMotionEvent]().load() 159 | 160 | def as_mousebutton(self) -> MouseButtonEvent: 161 | return Pointer.address_of(self).bitcast[MouseButtonEvent]().load() 162 | 163 | def as_mousewheel(self) -> MouseWheelEvent: 164 | return Pointer.address_of(self).bitcast[MouseWheelEvent]().load() 165 | 166 | 167 | #alias Event = Keyevent 168 | 169 | @register_passable('trivial') 170 | struct Keyevent: 171 | var type: UInt32 172 | var timestamp: UInt32 173 | var windowID: UInt32 174 | var state: UInt8 175 | var repeat: UInt8 176 | var padding2: UInt8 177 | var padding3: UInt8 178 | var keysym: Keysym 179 | 180 | def __init__(inout self) -> Self: 181 | #self.value = 0 182 | self.timestamp = 0 183 | self.windowID = 0 184 | self.state = 0 185 | self.repeat = 0 186 | self.padding2 = 0 187 | self.padding3 = 0 188 | 189 | 190 | # SDL.h 191 | alias c_SDL_Init = fn(w: Int32) -> Int32 192 | alias c_SDL_Quit = fn() -> None 193 | 194 | # SDL_video.h 195 | alias c_SDL_CreateWindow = fn(DTypePointer[DType.int8], Int32, Int32, Int32, Int32, Int32) -> Pointer[SDL_Window] 196 | alias c_SDL_DestroyWindow = fn(Pointer[SDL_Window]) -> None 197 | alias c_SDL_GetWindowSurface = fn(s: Pointer[Int8]) -> Pointer[SDL_Surface] 198 | alias c_SDL_UpdateWindowSurface = fn(s: Pointer[Int8]) -> Int32 199 | 200 | # SDL_pixels.h 201 | alias c_SDL_MapRGB = fn(Int32, Int32, Int32, Int32) -> UInt32 202 | 203 | # SDL_timer.h 204 | alias c_SDL_Delay = fn(Int32) -> UInt32 205 | 206 | # SDL_event.h 207 | alias c_SDL_PollEvent = fn(Pointer[Event]) -> Int32 208 | 209 | # SDL_render.h 210 | alias c_SDL_CreateRenderer = fn(Pointer[SDL_Window], Int32, UInt32) -> Pointer[SDL_Renderer] 211 | alias c_SDL_CreateWindowAndRenderer = fn(Int32, Int32, UInt32, Pointer[Pointer[Int8]], Pointer[Pointer[SDL_Renderer]]) -> Int32 212 | alias c_SDL_RenderDrawPoint = fn(Pointer[SDL_Renderer], Int32, Int32) -> Int32 213 | alias c_SDL_RenderDrawRect = fn(r: Pointer[SDL_Renderer], rect: Pointer[SDL_Rect]) -> Int32 214 | alias c_SDL_RenderPresent = fn(s: Pointer[SDL_Renderer]) -> Int32 215 | alias c_SDL_RenderClear = fn(s: Pointer[SDL_Renderer]) -> Int32 216 | alias c_SDL_SetRenderDrawColor = fn(Pointer[SDL_Renderer], UInt8, UInt8, UInt8, UInt8) -> Int32 217 | alias SDL_BlendMode = Int 218 | alias c_SDL_SetRenderDrawBlendMode = fn(Pointer[SDL_Renderer], SDL_BlendMode) -> Int32 219 | alias c_SDL_SetRenderTarget = fn(r: Pointer[SDL_Renderer], 220 | # t: Pointer[SDL_Texture]) -> Int32 221 | t: Int64) -> Int32 222 | 223 | alias c_SDL_RenderCopy = fn(r: Pointer[SDL_Renderer], 224 | t: Int64, #t: Pointer[SDL_Texture], 225 | s: Int64, d: Int64) -> Int32 226 | #s: Pointer[SDL_Rect], d: Pointer[SDL_Rect]) -> Int32 227 | 228 | # SDL_surface.h 229 | alias c_SDL_FillRect = fn(Pointer[SDL_Surface], Int64, UInt32) -> Int32 230 | 231 | 232 | # texture 233 | alias c_SDL_CreateTexture = fn(Pointer[SDL_Renderer], 234 | UInt32, Int32, 235 | Int32, Int32) -> Int64 #Pointer[SDL_Texture] 236 | 237 | 238 | 239 | alias SDL_WINDOWPOS_UNDEFINED = 0x1FFF0000 240 | 241 | alias SDL_WINDOW_SHOWN = 0x00000004 242 | 243 | 244 | struct SDL: 245 | var Init: c_SDL_Init 246 | var Quit: c_SDL_Quit 247 | 248 | var CreateWindow: c_SDL_CreateWindow 249 | var DestroyWindow: c_SDL_DestroyWindow 250 | 251 | var GetWindowSurface: c_SDL_GetWindowSurface 252 | var UpdateWindowSurface: c_SDL_UpdateWindowSurface 253 | var CreateRenderer: c_SDL_CreateRenderer 254 | var CreateWindowAndRenderer: c_SDL_CreateWindowAndRenderer 255 | var RenderDrawPoint: c_SDL_RenderDrawPoint 256 | var RenderDrawRect: c_SDL_RenderDrawRect 257 | var SetRenderDrawColor: c_SDL_SetRenderDrawColor 258 | var RenderPresent: c_SDL_RenderPresent 259 | var RenderClear: c_SDL_RenderClear 260 | var CreateTexture: c_SDL_CreateTexture 261 | var SetRenderDrawBlendMode: c_SDL_SetRenderDrawBlendMode 262 | var SetRenderTarget: c_SDL_SetRenderTarget 263 | var RenderCopy: c_SDL_RenderCopy 264 | 265 | var MapRGB: c_SDL_MapRGB 266 | var FillRect: c_SDL_FillRect 267 | var Delay: c_SDL_Delay 268 | var PollEvent: c_SDL_PollEvent 269 | 270 | fn __init__(inout self): 271 | print("binding SDL") 272 | var lib_path = get_sdl_lib_path() 273 | #let SDL = ffi.DLHandle('/usr/lib64/libSDL2.so') 274 | var SDL = ffi.DLHandle(lib_path) 275 | 276 | self.Init = SDL.get_function[c_SDL_Init]('SDL_Init') 277 | self.Quit = SDL.get_function[c_SDL_Quit]('SDL_Quit') 278 | 279 | self.CreateWindow = SDL.get_function[c_SDL_CreateWindow]('SDL_CreateWindow') 280 | self.DestroyWindow = SDL.get_function[c_SDL_DestroyWindow]('SDL_DestroyWindow') 281 | 282 | self.GetWindowSurface = SDL.get_function[c_SDL_GetWindowSurface]('SDL_GetWindowSurface') 283 | self.UpdateWindowSurface = SDL.get_function[c_SDL_UpdateWindowSurface]('SDL_UpdateWindowSurface') 284 | 285 | self.CreateRenderer = SDL.get_function[c_SDL_CreateRenderer]('SDL_CreateRenderer') 286 | self.CreateWindowAndRenderer = SDL.get_function[c_SDL_CreateWindowAndRenderer]('SDL_CreateWindowAndRenderer') 287 | self.RenderDrawPoint = SDL.get_function[c_SDL_RenderDrawPoint]('SDL_RenderDrawPoint') 288 | self.RenderDrawRect = SDL.get_function[c_SDL_RenderDrawRect]('SDL_RenderDrawRect') 289 | self.SetRenderDrawColor = SDL.get_function[c_SDL_SetRenderDrawColor]('SDL_SetRenderDrawColor') 290 | self.RenderPresent = SDL.get_function[c_SDL_RenderPresent]('SDL_RenderPresent') 291 | self.RenderClear = SDL.get_function[c_SDL_RenderClear]('SDL_RenderClear') 292 | self.SetRenderDrawBlendMode = SDL.get_function[c_SDL_SetRenderDrawBlendMode]('SDL_SetRenderDrawBlendMode') 293 | self.SetRenderTarget = SDL.get_function[c_SDL_SetRenderTarget]('SDL_SetRenderTarget') 294 | self.RenderCopy = SDL.get_function[c_SDL_RenderCopy]('SDL_RenderCopy') 295 | 296 | self.CreateTexture = SDL.get_function[c_SDL_CreateTexture]('SDL_CreateTexture') 297 | 298 | 299 | self.MapRGB = SDL.get_function[c_SDL_MapRGB]('SDL_MapRGB') 300 | self.FillRect = SDL.get_function[c_SDL_FillRect]('SDL_FillRect') 301 | self.Delay = SDL.get_function[c_SDL_Delay]('SDL_Delay') 302 | self.PollEvent = SDL.get_function[c_SDL_PollEvent]('SDL_PollEvent') 303 | -------------------------------------------------------------------------------- /cmap.mojo: -------------------------------------------------------------------------------- 1 | alias vec3 = StaticTuple[3] 2 | alias cmap = StaticTuple[256] ( 3 | vec3(0, 0, 0), 4 | vec3(2, 0, 0), 5 | vec3(4, 0, 0), 6 | vec3(6, 0, 0), 7 | vec3(8, 0, 0), 8 | vec3(10, 0, 0), 9 | vec3(12, 0, 0), 10 | vec3(14, 0, 0), 11 | vec3(16, 0, 0), 12 | vec3(18, 0, 0), 13 | vec3(20, 0, 0), 14 | vec3(22, 0, 0), 15 | vec3(24, 0, 0), 16 | vec3(26, 0, 0), 17 | vec3(28, 0, 0), 18 | vec3(30, 0, 0), 19 | vec3(32, 0, 0), 20 | vec3(34, 0, 0), 21 | vec3(36, 0, 0), 22 | vec3(38, 0, 0), 23 | vec3(40, 0, 0), 24 | vec3(42, 0, 0), 25 | vec3(44, 0, 0), 26 | vec3(46, 0, 0), 27 | vec3(48, 0, 0), 28 | vec3(50, 0, 0), 29 | vec3(52, 0, 0), 30 | vec3(54, 0, 0), 31 | vec3(56, 0, 0), 32 | vec3(58, 0, 0), 33 | vec3(60, 0, 0), 34 | vec3(62, 0, 0), 35 | vec3(64, 0, 0), 36 | vec3(65, 0, 0), 37 | vec3(68, 0, 0), 38 | vec3(70, 0, 0), 39 | vec3(72, 0, 0), 40 | vec3(73, 0, 0), 41 | vec3(76, 0, 0), 42 | vec3(78, 0, 0), 43 | vec3(80, 0, 0), 44 | vec3(81, 0, 0), 45 | vec3(84, 0, 0), 46 | vec3(86, 0, 0), 47 | vec3(88, 0, 0), 48 | vec3(89, 0, 0), 49 | vec3(92, 0, 0), 50 | vec3(94, 0, 0), 51 | vec3(96, 0, 0), 52 | vec3(97, 0, 0), 53 | vec3(100, 0, 0), 54 | vec3(102, 0, 0), 55 | vec3(104, 0, 0), 56 | vec3(105, 0, 0), 57 | vec3(108, 0, 0), 58 | vec3(110, 0, 0), 59 | vec3(112, 0, 0), 60 | vec3(113, 0, 0), 61 | vec3(116, 0, 0), 62 | vec3(118, 0, 0), 63 | vec3(120, 0, 0), 64 | vec3(121, 0, 0), 65 | vec3(124, 0, 0), 66 | vec3(126, 0, 0), 67 | vec3(128, 0, 0), 68 | vec3(130, 2, 0), 69 | vec3(131, 4, 0), 70 | vec3(134, 6, 0), 71 | vec3(136, 8, 0), 72 | vec3(138, 10, 0), 73 | vec3(140, 12, 0), 74 | vec3(142, 14, 0), 75 | vec3(144, 16, 0), 76 | vec3(146, 18, 0), 77 | vec3(147, 20, 0), 78 | vec3(150, 22, 0), 79 | vec3(152, 24, 0), 80 | vec3(154, 26, 0), 81 | vec3(156, 28, 0), 82 | vec3(158, 30, 0), 83 | vec3(160, 32, 0), 84 | vec3(162, 34, 0), 85 | vec3(163, 36, 0), 86 | vec3(166, 38, 0), 87 | vec3(168, 40, 0), 88 | vec3(170, 42, 0), 89 | vec3(172, 44, 0), 90 | vec3(174, 46, 0), 91 | vec3(176, 48, 0), 92 | vec3(178, 50, 0), 93 | vec3(179, 52, 0), 94 | vec3(182, 54, 0), 95 | vec3(184, 56, 0), 96 | vec3(186, 58, 0), 97 | vec3(188, 60, 0), 98 | vec3(190, 62, 0), 99 | vec3(192, 64, 0), 100 | vec3(194, 66, 0), 101 | vec3(195, 68, 0), 102 | vec3(198, 70, 0), 103 | vec3(200, 72, 0), 104 | vec3(202, 74, 0), 105 | vec3(204, 76, 0), 106 | vec3(206, 78, 0), 107 | vec3(208, 80, 0), 108 | vec3(210, 82, 0), 109 | vec3(211, 84, 0), 110 | vec3(214, 86, 0), 111 | vec3(216, 88, 0), 112 | vec3(218, 90, 0), 113 | vec3(220, 92, 0), 114 | vec3(222, 94, 0), 115 | vec3(224, 96, 0), 116 | vec3(226, 98, 0), 117 | vec3(227, 100, 0), 118 | vec3(230, 102, 0), 119 | vec3(232, 104, 0), 120 | vec3(234, 106, 0), 121 | vec3(236, 108, 0), 122 | vec3(238, 110, 0), 123 | vec3(240, 112, 0), 124 | vec3(242, 114, 0), 125 | vec3(243, 116, 0), 126 | vec3(246, 118, 0), 127 | vec3(248, 120, 0), 128 | vec3(250, 122, 0), 129 | vec3(252, 124, 0), 130 | vec3(254, 126, 0), 131 | vec3(255, 128, 0), 132 | vec3(255, 130, 2), 133 | vec3(255, 132, 4), 134 | vec3(255, 134, 6), 135 | vec3(255, 136, 8), 136 | vec3(255, 138, 11), 137 | vec3(255, 140, 13), 138 | vec3(255, 142, 15), 139 | vec3(255, 144, 16), 140 | vec3(255, 146, 18), 141 | vec3(255, 148, 20), 142 | vec3(255, 150, 22), 143 | vec3(255, 152, 25), 144 | vec3(255, 154, 27), 145 | vec3(255, 156, 29), 146 | vec3(255, 158, 31), 147 | vec3(255, 160, 32), 148 | vec3(255, 162, 34), 149 | vec3(255, 164, 36), 150 | vec3(255, 166, 38), 151 | vec3(255, 168, 40), 152 | vec3(255, 170, 43), 153 | vec3(255, 172, 45), 154 | vec3(255, 174, 47), 155 | vec3(255, 176, 48), 156 | vec3(255, 178, 50), 157 | vec3(255, 180, 52), 158 | vec3(255, 182, 54), 159 | vec3(255, 184, 57), 160 | vec3(255, 186, 59), 161 | vec3(255, 188, 61), 162 | vec3(255, 190, 63), 163 | vec3(255, 192, 65), 164 | vec3(255, 194, 66), 165 | vec3(255, 196, 68), 166 | vec3(255, 198, 70), 167 | vec3(255, 200, 72), 168 | vec3(255, 202, 75), 169 | vec3(255, 204, 77), 170 | vec3(255, 206, 79), 171 | vec3(255, 208, 81), 172 | vec3(255, 210, 82), 173 | vec3(255, 212, 84), 174 | vec3(255, 214, 86), 175 | vec3(255, 216, 89), 176 | vec3(255, 218, 91), 177 | vec3(255, 220, 93), 178 | vec3(255, 222, 95), 179 | vec3(255, 224, 97), 180 | vec3(255, 226, 98), 181 | vec3(255, 228, 100), 182 | vec3(255, 230, 102), 183 | vec3(255, 232, 104), 184 | vec3(255, 234, 107), 185 | vec3(255, 236, 109), 186 | vec3(255, 238, 111), 187 | vec3(255, 240, 113), 188 | vec3(255, 242, 114), 189 | vec3(255, 244, 116), 190 | vec3(255, 246, 118), 191 | vec3(255, 248, 121), 192 | vec3(255, 250, 123), 193 | vec3(255, 252, 125), 194 | vec3(255, 254, 127), 195 | vec3(255, 255, 129), 196 | vec3(255, 255, 131), 197 | vec3(255, 255, 132), 198 | vec3(255, 255, 134), 199 | vec3(255, 255, 136), 200 | vec3(255, 255, 139), 201 | vec3(255, 255, 141), 202 | vec3(255, 255, 143), 203 | vec3(255, 255, 145), 204 | vec3(255, 255, 147), 205 | vec3(255, 255, 148), 206 | vec3(255, 255, 150), 207 | vec3(255, 255, 153), 208 | vec3(255, 255, 155), 209 | vec3(255, 255, 157), 210 | vec3(255, 255, 159), 211 | vec3(255, 255, 161), 212 | vec3(255, 255, 163), 213 | vec3(255, 255, 164), 214 | vec3(255, 255, 166), 215 | vec3(255, 255, 168), 216 | vec3(255, 255, 171), 217 | vec3(255, 255, 173), 218 | vec3(255, 255, 175), 219 | vec3(255, 255, 177), 220 | vec3(255, 255, 179), 221 | vec3(255, 255, 180), 222 | vec3(255, 255, 182), 223 | vec3(255, 255, 185), 224 | vec3(255, 255, 187), 225 | vec3(255, 255, 189), 226 | vec3(255, 255, 191), 227 | vec3(255, 255, 193), 228 | vec3(255, 255, 195), 229 | vec3(255, 255, 196), 230 | vec3(255, 255, 198), 231 | vec3(255, 255, 200), 232 | vec3(255, 255, 203), 233 | vec3(255, 255, 205), 234 | vec3(255, 255, 207), 235 | vec3(255, 255, 209), 236 | vec3(255, 255, 211), 237 | vec3(255, 255, 212), 238 | vec3(255, 255, 214), 239 | vec3(255, 255, 217), 240 | vec3(255, 255, 219), 241 | vec3(255, 255, 221), 242 | vec3(255, 255, 223), 243 | vec3(255, 255, 225), 244 | vec3(255, 255, 227), 245 | vec3(255, 255, 228), 246 | vec3(255, 255, 230), 247 | vec3(255, 255, 232), 248 | vec3(255, 255, 235), 249 | vec3(255, 255, 237), 250 | vec3(255, 255, 239), 251 | vec3(255, 255, 241), 252 | vec3(255, 255, 243), 253 | vec3(255, 255, 244), 254 | vec3(255, 255, 246), 255 | vec3(255, 255, 249), 256 | vec3(255, 255, 251), 257 | vec3(255, 255, 253), 258 | vec3(255, 255, 255), 259 | ) 260 | -------------------------------------------------------------------------------- /gencmap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | import matplotlib as mpl 5 | 6 | cmap_name = 'afmhot' 7 | if len(sys.argv) > 1: 8 | cmap_name = sys.argv[1] 9 | 10 | cmap8bit = mpl.colormaps[cmap_name].resampled(256) 11 | 12 | print("alias vec3 = StaticTuple[3]") 13 | print("alias cmap = StaticTuple[256] (") 14 | for i in range(256): 15 | c = cmap8bit(i) 16 | print(f'vec3({int(c[0]*255)}, {int(c[1]*255)}, {int(c[2]*255)}),') 17 | print(')') 18 | -------------------------------------------------------------------------------- /mandelbrot.mojo: -------------------------------------------------------------------------------- 1 | # ===----------------------------------------------------------------------=== # 2 | # Copyright (c) 2023, Modular Inc. All rights reserved. 3 | # 4 | # Licensed under the Apache License v2.0 with LLVM Exceptions: 5 | # https://llvm.org/LICENSE.txt 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | # ===----------------------------------------------------------------------=== # 13 | 14 | import benchmark 15 | from complex import ComplexSIMD, ComplexFloat64 16 | from math import iota, clamp, log, pow 17 | from python import Python 18 | from algorithm import parallelize, vectorize 19 | from tensor import Tensor 20 | from utils.index import Index 21 | 22 | from memory.unsafe import bitcast 23 | from SDL import * 24 | from cmap import cmap 25 | 26 | alias float_type = DType.float64 27 | alias simd_width = 2 * simdwidthof[float_type]() 28 | 29 | alias width = 480 30 | alias height = 480 31 | alias MAX_ITERS = 500 32 | 33 | alias MIN_X = -2.0 34 | alias MAX_X = 0.6 35 | alias MIN_Y = -1.5 36 | alias MAX_Y = 1.5 37 | 38 | @no_inline 39 | fn mandelbrot_kernel_SIMD[ 40 | simd_width: Int 41 | ](c: ComplexSIMD[float_type, simd_width]) -> SIMD[float_type, simd_width]: 42 | """A vectorized implementation of the inner mandelbrot computation.""" 43 | var cx = c.re 44 | var cy = c.im 45 | var x = SIMD[float_type, simd_width](0) 46 | var y = SIMD[float_type, simd_width](0) 47 | var y2 = SIMD[float_type, simd_width](0) 48 | var iters = SIMD[float_type, simd_width](0) 49 | 50 | var t: SIMD[DType.bool, simd_width] = True 51 | for i in range(MAX_ITERS): 52 | if not t.reduce_or(): 53 | break 54 | y2 = y * y 55 | y = x.fma(y + y, cy) 56 | t = x.fma(x, y2) <= 4 57 | x = x.fma(x, cx - y2) 58 | iters = t.select(iters + 1, iters) 59 | return iters 60 | 61 | 62 | fn main() raises: 63 | 64 | var t = Tensor[float_type](height, width) 65 | 66 | var min_x: Float64 = MIN_X 67 | var max_x: Float64 = MAX_X 68 | var min_y: Float64 = MIN_Y 69 | var max_y: Float64 = MAX_Y 70 | 71 | @parameter 72 | @no_inline 73 | fn worker(row: Int): 74 | var scale_x = (max_x - min_x) / width 75 | var scale_y = (max_y - min_y) / height 76 | 77 | #print(scale_x) 78 | @parameter 79 | @no_inline 80 | fn compute_vector[simd_width: Int](col: Int): 81 | """Each time we operate on a `simd_width` vector of pixels.""" 82 | var cx = min_x + (col + iota[float_type, simd_width]()) * scale_x 83 | var cy = min_y + row * scale_y 84 | var c = ComplexSIMD[float_type, simd_width](cx, cy) 85 | t.data().simd_store[simd_width]( 86 | row * width + col, mandelbrot_kernel_SIMD[simd_width](c) 87 | ) 88 | 89 | # Vectorize the call to compute_vector where call gets a chunk of pixels. 90 | vectorize[compute_vector, simd_width, width](width) 91 | 92 | _ = t # Make sure tensor isn't destroyed before benchmark is finished 93 | 94 | var sdl = SDL() 95 | 96 | var res = sdl.Init(0x00000020) 97 | var window = sdl.CreateWindow(StringRef("Mandelbrot").data, 98 | SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 99 | width, height, SDL_WINDOW_SHOWN) 100 | 101 | var renderer = sdl.CreateRenderer(window, -1, 0) 102 | 103 | var display = sdl.CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height) 104 | 105 | _ = sdl.SetRenderTarget(renderer, display) 106 | 107 | fn redraw(sdl: SDL, t: Tensor[float_type]) raises: 108 | var gamma: Float64 = 0.3 109 | var cpow_max = pow(Float64(MAX_ITERS),gamma) 110 | _ = sdl.SetRenderTarget(renderer, display) 111 | for y in range(t.shape()[1]): 112 | for x in range(t.shape()[0]): 113 | var val = t[x,y] 114 | var cpow = pow(val, gamma) 115 | var color = cmap[(255.0*cpow/cpow_max).to_int()] 116 | var r = color[0] 117 | var g = color[1] 118 | var b = color[2] 119 | _ = sdl.SetRenderDrawColor(renderer, r, g, b, 255) 120 | _ = sdl.RenderDrawPoint(renderer, y, x) 121 | 122 | _ = sdl.SetRenderTarget(renderer, 0) 123 | _ = sdl.RenderCopy(renderer, display, 0, 0) 124 | _ = sdl.RenderPresent(renderer) 125 | 126 | var event = Event() 127 | 128 | 129 | fn screen_to_world(sx: Int32, sy: Int32, inout wx: Float64, inout wy: Float64): 130 | var fsx = sx.cast[DType.float64]() 131 | var fsy = sy.cast[DType.float64]() 132 | wx = (max_x - min_x) * fsx/Float64(width) + min_x 133 | wy = (max_y - min_y) * fsy/Float64(height) + min_y 134 | 135 | var running = True 136 | var dirty = True 137 | 138 | while running: 139 | 140 | while sdl.PollEvent(Pointer[Event].address_of(event)) != 0: 141 | if (event.type == SDL_MOUSEWHEEL): 142 | var mwe = event.as_mousewheel() 143 | #print(mwe.preciseX, mwe.preciseY) 144 | var scale = (1 + mwe.preciseY.cast[DType.float64]() / 20.0) 145 | min_x = (min_x * scale) 146 | max_x = (max_x * scale) 147 | min_y = (min_y * scale) 148 | max_y = (max_y * scale) 149 | dirty = True 150 | if (event.type == SDL_QUIT): 151 | running = False 152 | break 153 | 154 | if dirty: 155 | parallelize[worker](height, height) 156 | 157 | dirty = False 158 | redraw(sdl, t) 159 | 160 | _= sdl.Delay((1000 / 120).to_int()) 161 | 162 | _ = t 163 | sdl.DestroyWindow(window) 164 | sdl.Quit() 165 | --------------------------------------------------------------------------------