Code Monkey home page Code Monkey logo

sdl's Introduction

sdl

sdl is a SDL2 V module and a wrapper around libSDL2.

The module strives to support 100% of the SDL2 API.

So, among many other things, you can:

  • Open windows and accelerated rendering contexts
  • Render basic 2D graphics
  • Handle input events from keyboards, touches, mice, gamepads and joysticks
  • Play audio, sound effects and music

Install

If you want to use SDL2 v2.0.8 you can simply do:

v install sdl

If you want to use another version of SDL2 you will, currently, have to install it via git or by manual download.

An example of installing the system provided version of SDL2 via git:

git clone https://github.com/vlang/sdl.git ~/.vmodules/sdl
v ~/.vmodules/sdl/setup.vsh

Should sdl2-config be absent on your system you can try the following instead, by providing the version manually:

An example of installing SDL2 v2.0.12 via git:

git clone https://github.com/vlang/sdl.git ~/.vmodules/sdl
cd ~/.vmodules/sdl
git checkout 2.0.12

and for Windows:

git clone https://github.com/vlang/sdl.git %HOMEPATH%/.vmodules/sdl
cd %HOMEPATH%/.vmodules/sdl
git checkout 2.0.12

Then follow the steps in the Windows section below.

You can see what sdl releases are available in the GitHub repository via branches.

Also note that you'll need the SDL2 libraries available on your system see the Dependencies section below for more details.

Version notes

SDL2 v2.0.8 is currently the lowest version of SDL2 supported. SDL2 is backwards compatible - so anything written against v2.0.8 can be compiled and run against newer versions of the SDL2 library.

Also note that SDL2 is not compatible with SDL v1.x.

Notes on garbage collection and memory issues

Currently, with some setups, SDL2 is known to trigger crashes when used in conjunction with V's default garbage collector. In these cases running apps importing sdl with v run you may experience runtime crashes and output similar to this:

main__main: RUNTIME ERROR: invalid memory access

We are tracking the issue here: #744

The crashes can be avoided by passing -d sdl_memory_no_gc when compiling V applications that contains import sdl and managing SDL2's memory manually with calls to the various destroy and sdl.free/1 functions.

Support

sdl is currently supported on:

Examples

tVintris

tVintris screenshot

You can run the tVintris example like this :

v run sdl/examples/tvintris/tvintris.v

Dependencies

Linux

Fedora

sudo dnf install SDL2-devel SDL2_ttf-devel SDL2_mixer-devel SDL2_image-devel

Ubuntu

sudo apt install libsdl2-ttf-dev libsdl2-mixer-dev libsdl2-image-dev

Arch

sudo pacman -S sdl2 sdl2_image sdl2_mixer sdl2_ttf

ClearLinux

sudo swupd bundle-add devpkg-SDL2_ttf devpkg-SDL2_mixer devpkg-SDL2_image

MacOS

Brew

brew install sdl2 sdl2_gfx sdl2_ttf sdl2_mixer sdl2_image sdl2_net

If you get no music with the above, try:

brew reinstall --build-from-source --force sdl2 sdl2_gfx sdl2_image sdl2_mixer sdl2_net sdl2_ttf webp libtiff libmodplug libogg

Windows

It is necessary to install the sdl2 development libraries for Windows. To do this, change to the root directory of the sdl module, like cd %HOMEPATH%\.vmodules\sdl and run v run windows_install_dependencies.vsh. This will create a directory called "thirdparty" which will be used to download and extract the required libraries. To successfully run a provided example or your own projects, the sdl dlls must be copied to the main application directory. e.g.:

copy thirdparty\SDL2-2.0.8\lib\x64\SDL2.dll examples\basic_window\
cd ..
v run sdl\examples\basic_window\main.v

Contributions

  • nsauzede
  • spytheman
  • adlesh
  • Larpon

sdl's People

Contributors

abughurab16 avatar delta456 avatar ekopalypse avatar hungrybluedev avatar jalonsolov avatar keitotobi1 avatar larpon avatar leon-arndt avatar medvednikov avatar pottierloic avatar shove70 avatar spytheman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdl's Issues

Example of sdl/sokol not working on windows?

V doctor:

OS: windows, Microsoft Windows 11 Home v22000 64-bit
Processor: 16 cpus, 64bit, little endian, AMD Ryzen 9 5900HS with Radeon Graphics  

CC version: Error: exec failed (CreateProcess) with code 2: The system cannot find the file specified.

 cmd: cc --version

getwd: C:\Users\AMigh\Desktop\V\vivid\test
vmodules: C:\Users\AMigh\.vmodules
vroot: E:\Languages\v
vexe: E:\Languages\v\v.exe
vexe mtime: 2022-04-12 14:14:00
is vroot writable: true
is vmodules writable: true
V full version: V 0.2.4 6718958

Git version: git version 2.36.0.windows.1
Git vroot status: Error: fatal: not a git repository (or any of the parent directories): .git
.git/config present: false
thirdparty/tcc: N/A

What did you do?
v -g -o vdbg cmd/v && vdbg main.v

// Copyright(C) 2022 Lars Pontoppidan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module main

import sdl
import sokol.gfx

#flag -I @VMODROOT/.
#include "example_shader.h"

fn C.example_shader_desc(gfx.Backend) &gfx.ShaderDesc

// Vertex_t makes it possible to model vertex buffer data
// for use with the shader system
struct Vertex_t {
	// Position
	x f32
	y f32
	z f32
	// Color
	r f32
	g f32
	b f32
	a f32
}

[console]
fn main() {
	sdl.init(sdl.init_video)

	sdl.gl_set_attribute(.context_flags, int(sdl.GLcontextFlag.forward_compatible_flag))
	sdl.gl_set_attribute(.context_profile_mask, int(sdl.GLprofile.core))
	sdl.gl_set_attribute(.context_major_version, 3)
	sdl.gl_set_attribute(.context_minor_version, 3)
	sdl.gl_set_attribute(.doublebuffer, 1)
	sdl.gl_set_attribute(.depth_size, 24)
	sdl.gl_set_attribute(.stencil_size, 8)

	mut window_flags := u32(sdl.WindowFlags.opengl)
	window := sdl.create_window('Hello SDL2 + Sokol (OpenGL)'.str, 300, 300, 500, 300,
		window_flags)
	if window == sdl.null {
		error_msg := unsafe { cstring_to_vstring(sdl.get_error()) }
		panic('Could not create SDL window, SDL says:\n$error_msg')
	}

	gl_context := sdl.gl_create_context(window)
	if gl_context == sdl.null {
		error_msg := unsafe { cstring_to_vstring(sdl.get_error()) }
		panic('Could not create OpenGL context, SDL says:\n$error_msg')
	}

	sdl.gl_make_current(window, gl_context)
	// Enable VSYNC (Sync buffer swaps with monitors vertical refresh rate)
	if sdl.gl_set_swap_interval(1) < 0 {
		error_msg := unsafe { cstring_to_vstring(sdl.get_error()) }
		panic('Could not set OpenGL swap interval to vsync:\n$error_msg')
	}

	desc := gfx.Desc{}
	gfx.setup(&desc)
	assert gfx.is_valid() == true

	pass_action := gfx.create_clear_pass(0.0, 0.0, 0.0, 1.0)
	mut bind := gfx.Bindings{}

	vertices := [
		Vertex_t{0.0, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0},
		Vertex_t{0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 1.0},
		Vertex_t{-0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0},
	]

	mut vertex_buffer_desc := gfx.BufferDesc{
		label: c'triangle-vertices'
	}
	unsafe { vmemset(&vertex_buffer_desc, 0, int(sizeof(vertex_buffer_desc))) }

	vertex_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
	vertex_buffer_desc.data = gfx.Range{
		ptr: vertices.data
		size: vertex_buffer_desc.size
	}

	bind.vertex_buffers[0] = gfx.make_buffer(&vertex_buffer_desc)

	shader := gfx.make_shader(C.example_shader_desc(gfx.query_backend()))

	mut pipeline_desc := gfx.PipelineDesc{}
	unsafe { vmemset(&pipeline_desc, 0, int(sizeof(pipeline_desc))) }

	pipeline_desc.shader = shader

	pipeline_desc.layout.attrs[C.ATTR_vs_position].format = .float3 // x,y,z as f32
	pipeline_desc.layout.attrs[C.ATTR_vs_color0].format = .float4 // r, g, b, a as f32

	pipeline_desc.label = c'triangle-pipeline'

	shader_pipeline := gfx.make_pipeline(&pipeline_desc)

	mut should_close := false

	mut w := 0
	mut h := 0
	for {
		evt := sdl.Event{}
		for 0 < sdl.poll_event(&evt) {
			match evt.@type {
				.quit { should_close = true }
				else {}
			}
		}
		if should_close {
			break
		}

		sdl.gl_get_drawable_size(window, &w, &h)
		gfx.begin_default_pass(&pass_action, w, h)

		gfx.apply_pipeline(shader_pipeline)
		gfx.apply_bindings(&bind)

		gfx.draw(0, 3, 1)
		gfx.end_pass()
		gfx.commit()

		sdl.gl_swap_window(window)
	}

	gfx.shutdown()
	sdl.gl_delete_context(gl_context)
	sdl.destroy_window(window)
	sdl.quit()
}

What did you expect to see?

An SDL2/Sokol example from the official vlang/sdl repo

What did you see instead?

==================
In file included from C:/Users/AMigh/.vmodules/sdl/thirdparty/SDL2-2.0.8/include/SDL_stdinc.h:31:
C:/Users/AMigh/.vmodules/sdl/thirdparty/SDL2-2.0.8/include/SDL_config.h:68: error: incompatible redefinition of 'size_t'
...
==================
(Use `v -cg` to print the entire error message)

builder error: 
==================
C error. This should never happen.

This is a compiler bug, please report it using `v bug file.v`.

https://github.com/vlang/v/issues/new/choose

You can also use #help on Discord: https://discord.gg/vlang

``v doc sdl`` error

Running V doc on this module causes this problem for me:

$ v doc sdl
.vmodules/sdl/sdl.v:98:29: error: unexpected name `byte`, expecting `,`
   96 | 
   97 | ///////////////////////////////////////////////////
   98 | fn C.SDL_MapRGB(fmt voidptr byte, g byte, b byte) u32
      |                             ~~~~
   99 | fn C.SDL_CreateRGBSurface(flags u32, width int, height int, depth int, Rmask u32, Gmask u32, Bmask u32, Amask u32) voidptr
  100 | fn C.SDL_PollEvent(&SDL_Event) int

Wrong module name in module 'vulkan'

V version: V 0.4.2 1c4c505
OS: linux, Linux version 6.5.9-200.fc38.x86_64 (mockbuild@1cc7d6d790524511abd343182a21832a) (gcc (GCC) 13.2.1 20231011 (Red Hat 13.2.1-4), GNU ld version 2.39-15.fc38) #1 SMP PREEMPT_DYNAMIC Wed Oct 25 20:40:49 UTC 2023

What did you do?
I tried to import module sdl.vulkan

What did you expect to see?
I expected functions inside module sdl.vulkan to be aknowledge by the compiler

What did you see instead?
I saw this error:

imports module "sdl.vulkan" but ~/.vmodules/sdl/vulkan/vulkan.c.v is defined as module `sdl`

Feature Request: Static SDL

Hello, nice job. Would you consider offering the possibility to statically link sdl to the binary ?
Maybe its but I'm missing something.
Thanks!

Basic window example crash

The basic_window example (and any other program that uses the module) crash with the message "free(): invalid pointer". I have installed the version of the module that corresponds to the SDL version of the system. Other programs using a SDL wrapper (in pascal) work without problems.

Error at run example

V version:
OS:

V full version: V 0.3.3 6e670ec.6e1e406
OS: windows, Microsoft Windows 10 Pro v19045 64-bit
Processor: 4 cpus, 64bit, little endian,

getwd: C:\Users\mlap\Documents\m\Installs\Vlang\sdl-master\examples\tvintris
vexe: C:\v\v.exe
vexe mtime: 2023-03-17 13:09:22

vroot: OK, value: C:\v
VMODULES: OK, value: C:\Users\mlap.vmodules
VTMP: OK, value: C:\Users\mlap\AppData\Local\Temp\v_0

Git version: git version 2.37.3.windows.1
Git vroot status: weekly.2022.40-990-g6e1e4062
.git/config present: true

CC version: Error: exec failed (CreateProcess) with code 2: The system cannot find the file specified. cmd: cc --version
thirdparty/tcc status: thirdparty-windows-amd64 1e6e7c6f

What did you do?

Try to run the example of sdl (after successfully v install sdl):
C:\Users\mlap\Documents\m\Installs\Vlang\sdl-master\examples\tvintris>v run .

What did you expect to see?

Must run visual tvintris.

What did you see instead?

INFO: compile with v -live . , if you want to use the [live] function draw_begin .
builder error: 'SDL.h' not found

With other examples - similar messages.

P.S. Please - write, what is this problem:

CC version: Error: exec failed (CreateProcess) with code 2: The system cannot find the file specified. cmd: cc --version

I installed v lang with its tcc, and all worked fine, I periodically successfully update all with v up and v update.

sdl crashes at runtime when used with V's garbage collector

In some cases, with some versions of SDL2, on some different distributions and platforms SDL2 crashes at runtime if applications are built using V's default garbage collector.

Currently, especially the tVintris example is known to cause different kind of crashes on different systems.

A, relatively simple, example MRE that crashes on my system (EndeavourOS, rolling, Arch based SDL v2.30.3 vlang/sdl branch 2.30.0):

module main

import sdl

struct Data1 {
mut:
	a int
}

fn main() {
	mut data1 := []&Data1{cap: 200}
	for i in 0 .. 200 {
		data1 << &Data1{
			a: i
		}
	}

	sdl.init(sdl.init_video)
	window := sdl.create_window('Hello SDL2'.str, 300, 300, 500, 300, 0)
	renderer := sdl.create_renderer(window, -1, u32(sdl.RendererFlags.accelerated) | u32(sdl.RendererFlags.presentvsync))

	mut should_close := false
	mut ticks := 0
	for {
		ticks++
		evt := sdl.Event{}
		for 0 < sdl.poll_event(&evt) {
			match evt.@type {
				.quit { should_close = true }
				else {}
			}
		}

		data1[0].a = ticks
		data1.delete(10)
		data1 << &Data1{
			a: ticks
		}

		println('ticks: ${ticks}')
		if should_close || ticks == 1000 {
			break
		}

		sdl.set_render_draw_color(renderer, 255, 55, 55, 255)
		sdl.render_clear(renderer)
		sdl.render_present(renderer)
	}
	println('Exiting. If this was compiled without `-d sdl_memory_no_gc`, an invalid memory access error should occur')

	sdl.destroy_renderer(renderer)
	sdl.destroy_window(window)
	sdl.quit()
}

We have introduced the compiletime flag: -d sdl_memory_no_gc to mitigate the problem. Usage of this flag also means that the user will have to manage SDL's memory manually by utilizing SDL2's destroy/sdl.free/1 functions.

The output when crashing is often similar to this:

main__main: RUNTIME ERROR: invalid memory access

Wrapper for SDL_RenderSetVSync

Could we get a wrapper for SDL_RenderSetVSync?

int SDL_RenderSetVSync(SDL_Renderer* renderer, int vsync) toggles the vsync of a renderer.

Thank you.

Basic window example returns C error

V version:
v 0.4.4 aeadc0a

OS:
Arcolinux 24.04.02 on KDE Plasma 6.0.1

What did you do?
v new try_sdl
then copied the basic window main.v
then v install sdl
and v run .

What did you expect to see?
a basic window

What did you see instead?

 las@lapsus  /backup/dev/v/scratchpad/try_sdl  v run .
==================
/tmp/v_1000/try_sdl.01HRWH9GNEA7V1BBTFE30QR0SK.tmp.c:1993: error: ';' expected (got "sdl__OSEvent")
...
==================
(Use `v -cg` to print the entire error message)

builder error: 
==================
C error. This should never happen.

This is a compiler bug, please report it using `v bug file.v`.

https://github.com/vlang/v/issues/new/choose

You can also use #help on Discord: https://discord.gg/vlang

Missing v.mod

/home/louis/.vmodules/medvednikov/sdl/sdl.v:19:3: error: To use @VROOT, you need to have a "v.mod" file in /home/louis/.vmodules/medvednikov/sdl, or in one of its parent folders. 
   17 | #flag windows -I @VROOT/thirdparty/SDL2/include
   18 | #flag windows -Dmain=SDL_main
   19 | #flag windows -lSDL2main -lSDL2
      |   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   20 | #flag windows -L @VROOT/thirdparty/SDL2/lib/x64
   21 |

Support for SDL_SysWMinfo

V version: does not apply
OS: does not apply

What did you do?
I tried to translate the following code

static void* sdlNativeWindowHandle(SDL_Window* _window)
{
  SDL_SysWMinfo wmi;
  SDL_VERSION(&wmi.version);
  if (!SDL_GetWindowWMInfo(_window, &wmi) )
  {
    return NULL;
  }
  ...
}

What did you expect to see?
I expected the sdl.SysWMinfo struct to exists in vsdl

What did you see instead?
The sdl.SysWMinfo struct does not exists in vsdl

AudioCallback function missing len parameter

In audio.c.v, I think the documented typedef was truncated, it shows:

// This function is called when the audio device needs more data.
...
// typedef void (SDLCALL * SDL_AudioCallback) (void *userdata, Uint8 * stream)

from the SDL headers it is defined

typedef void (SDLCALL * SDL_AudioCallback) (void *userdata, Uint8 * stream, int len);

And so, the real issue is, the function type for AudioCallback is missing the len parameter.

pub type AudioCallback = fn (userdata voidptr, stream &u8)

to

pub type AudioCallback = fn (userdata voidptr, stream &u8, len int)

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.