diff --git a/python/PySFML/__init__.py b/python/PySFML/__init__.py index 79d6660f..8b137891 100644 --- a/python/PySFML/__init__.py +++ b/python/PySFML/__init__.py @@ -1,2 +1 @@ -import sf diff --git a/python/samples/opengl.py b/python/samples/opengl.py index e35df9e5..b171a478 100644 --- a/python/samples/opengl.py +++ b/python/samples/opengl.py @@ -1,6 +1,6 @@ #!/usr/bin/python -from PySFML import * +from PySFML import sf from OpenGL.GL import * from OpenGL.GLUT import * diff --git a/python/samples/sound_capture.py b/python/samples/sound_capture.py index bfb24d0a..456ba59b 100644 --- a/python/samples/sound_capture.py +++ b/python/samples/sound_capture.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -from PySFML import * +from PySFML import sf def Main(): # Check that the device can capture audio diff --git a/python/samples/sound_capture_py3.py b/python/samples/sound_capture_py3.py new file mode 100644 index 00000000..2f2053da --- /dev/null +++ b/python/samples/sound_capture_py3.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python + +from PySFML import sf + +def Main(): + # Check that the device can capture audio + if sf.SoundRecorder.CanCapture() == False: + print("Sorry, audio capture is not supported by your system") + return + + # Choose the sample rate + SampleRate = int(input("Please choose the sample rate for sound capture (44100 is CD quality) : ")) + + # Wait for user input... + print("Press enter to start recording audio") + input() + + # Here we'll use an integrated custom recorder, which saves the captured data into a sfSoundBuffer + Recorder = sf.SoundBufferRecorder() + + # Audio capture is done in a separate thread, so we can block the main thread while it is capturing + Recorder.Start(SampleRate) + print("Recording... press enter to stop") + input() + Recorder.Stop() + + # Get the buffer containing the captured data + Buffer = Recorder.GetBuffer() + + # Display captured sound informations + print("Sound information :") + print(" " + str(Buffer.GetDuration()) + " seconds") + print(" " + str(Buffer.GetSampleRate()) + " samples / seconds") + print(" " + str(Buffer.GetChannelsCount()) + " channels") + + # Choose what to do with the recorded sound data + Choice = str(input("What do you want to do with captured sound (p = play, s = save) ? ")) + + if Choice == 's': + # Choose the filename + Filename = str(input("Choose the file to create : ")) + + # Save the buffer + Buffer.SaveToFile(Filename); + else: + # Create a sound instance and play it + Sound = sf.Sound(Buffer) + Sound.Play() + + # Wait until finished + while Sound.GetStatus() == sf.Sound.Playing: + # Display the playing position - I don't know how to do this in python + # std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec"; + + # Leave some CPU time for other threads + sf.Sleep(0.1) + + # Finished ! + print("Done !") + + # Wait until the user presses 'enter' key + print("Press enter to exit...") + input() + + return + +Main() diff --git a/python/samples/sound_stream_py3.py b/python/samples/sound_stream_py3.py new file mode 100755 index 00000000..9cae1279 --- /dev/null +++ b/python/samples/sound_stream_py3.py @@ -0,0 +1,49 @@ +#!/usr/bin/python + +from PySFML import sf + +class MyCustomStream(sf.SoundStream): + + def Open(self, Filename): + # Load the sound data into a sound buffer + self.SoundData = sf.SoundBuffer() + if not self.SoundData.LoadFromFile(Filename): + return False + # Initialize the stream with the sound parameters + self.Initialize(self.SoundData.GetChannelsCount(), self.SoundData.GetSampleRate()) + # Copy the audio samples into our internal array + self.myBuffer = self.SoundData.GetSamples() + return True + + def OnStart(self): + self.myOffset = 0 + self.myBufferSize = 80000 + return True + + def OnGetData(self): + # Check if there is enough data to stream + if self.myOffset > len(self.myBuffer): + # Returning something else than a string means that we want to stop playing the stream + return False + # Data contains the string of samples we will return + if self.myOffset + self.myBufferSize >= len(self.myBuffer): + print("End of audio data reached") + Data = self.myBuffer[self.myOffset:] + else: + Data = self.myBuffer[self.myOffset:self.myOffset+self.myBufferSize] + # Update the offset + self.myOffset = self.myBufferSize + self.myOffset + return Data + +def Main(): + Stream = MyCustomStream() + Stream.Open("./data/fart.wav") + Stream.Play() + print("Playing 5 seconds of audio data...") + sf.Sleep(5) + Stream.Stop() + print("Press enter to exit...") + input() + +Main() + diff --git a/python/samples/worm.py b/python/samples/worm.py index e43a9d92..2039f315 100644 --- a/python/samples/worm.py +++ b/python/samples/worm.py @@ -44,7 +44,8 @@ class Apple(sf.Sprite): def __init__(self): apple_img = sf.Image() # Apple's image if not apple_img.LoadFromFile("./data/apple.png"): - print "Could not load data/apple.png" + pass + # print "Could not load data/apple.png" sf.Sprite.__init__(self, apple_img) self.SetCenter(apple_img.GetWidth()/2, apple_img.GetHeight()/2) self.size = apple_img.GetWidth() @@ -109,7 +110,8 @@ class Worm(list): self.rond = sf.Image() self.level_completed = False if not self.rond.LoadFromFile("./data/rond2.png"): - print "Could not load data/rond2.png" + pass + # print "Could not load data/rond2.png" def reset(self, arena): self.targeted_length, self.angle, self.direction = 30, 0, 0 diff --git a/python/src/Drawable.cpp b/python/src/Drawable.cpp index d0fb7004..8f026c51 100644 --- a/python/src/Drawable.cpp +++ b/python/src/Drawable.cpp @@ -34,7 +34,9 @@ extern PyTypeObject PySfColorType; void CustomDrawable::Render (sf::RenderTarget& Target) const { if (RenderFunction) - PyObject_CallFunction(RenderFunction, (char *)"O", RenderWindow); + PyObject_CallFunction(RenderFunction, (char *)"O", RenderTarget); + else + PyErr_SetString(PyExc_RuntimeError, "Custom drawables must have a render method defined"); } static void @@ -48,23 +50,19 @@ static PyObject * PySfDrawable_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfDrawable *self; - self = (PySfDrawable *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } - static int PySfDrawable_init(PySfDrawable *self, PyObject *args, PyObject *kwds) { - self->obj = new CustomDrawable(); + self->obj = new CustomDrawable(); + self->obj->RenderFunction = NULL; + self->obj->RenderTarget = NULL; return 0; -} +} + static PyObject * PySfDrawable_SetX(PySfDrawable* self, PyObject *args) { @@ -81,7 +79,7 @@ static PyObject * PySfDrawable_SetScale(PySfDrawable* self, PyObject *args) { float ScaleX, ScaleY; - if ( !PyArg_ParseTuple(args, "ff", &ScaleX, &ScaleY) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.SetScale", &ScaleX, &ScaleY) ) return NULL; self->obj->SetScale(ScaleX, ScaleY); Py_RETURN_NONE; @@ -109,7 +107,7 @@ static PyObject * PySfDrawable_SetCenter(PySfDrawable* self, PyObject *args) { float x, y; - if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.SetCenter", &x, &y) ) return NULL; self->obj->SetCenter(x, y); Py_RETURN_NONE; @@ -127,7 +125,7 @@ PySfDrawable_SetColor(PySfDrawable* self, PyObject *args) PySfColor *Color = (PySfColor *)args; if (! PyObject_TypeCheck(args, &PySfColorType)) { - PyErr_SetString(PyExc_TypeError, "Argument is not a sfColor"); + PyErr_SetString(PyExc_TypeError, "Drawable.SetColor() Argument is not a sf.Color"); return NULL; } PySfColorUpdate(Color); @@ -170,7 +168,7 @@ static PyObject * PySfDrawable_Move(PySfDrawable* self, PyObject *args) { float x, y; - if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.Move", &x, &y) ) return NULL; self->obj->Move(x, y); Py_RETURN_NONE; @@ -185,7 +183,7 @@ static PyObject * PySfDrawable_Scale(PySfDrawable* self, PyObject *args) { float FactorX, FactorY; - if ( !PyArg_ParseTuple(args, "ff", &FactorX, &FactorY) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.Scale", &FactorX, &FactorY) ) return NULL; self->obj->Scale(FactorX, FactorY); Py_RETURN_NONE; @@ -202,7 +200,7 @@ static PyObject * PySfDrawable_SetPosition(PySfDrawable* self, PyObject *args) { float Left, Top; - if ( !PyArg_ParseTuple(args, "ff", &Left, &Top) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.SetPosition", &Left, &Top) ) return NULL; self->obj->SetPosition(Left, Top); Py_RETURN_NONE; @@ -212,7 +210,7 @@ static PyObject * PySfDrawable_TransformToLocal(PySfDrawable* self, PyObject *args) { float X, Y; - if ( !PyArg_ParseTuple(args, "ff", &X, &Y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.TransformToLocal", &X, &Y) ) return NULL; sf::Vector2f result = self->obj->TransformToLocal(sf::Vector2f(X, Y)); return Py_BuildValue("ff", result.x, result.y); @@ -222,7 +220,7 @@ static PyObject * PySfDrawable_TransformToGlobal(PySfDrawable* self, PyObject *args) { float X, Y; - if ( !PyArg_ParseTuple(args, "ff", &X, &Y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.TransformToGlobal", &X, &Y) ) return NULL; sf::Vector2f result = self->obj->TransformToGlobal(sf::Vector2f(X, Y)); return Py_BuildValue("ff", result.x, result.y); diff --git a/python/src/Drawable.hpp b/python/src/Drawable.hpp index 6e227271..abedd8ea 100644 --- a/python/src/Drawable.hpp +++ b/python/src/Drawable.hpp @@ -29,7 +29,7 @@ #include -#include "RenderWindow.hpp" +#include "RenderTarget.hpp" class CustomDrawable : public sf::Drawable @@ -37,7 +37,7 @@ class CustomDrawable : public sf::Drawable protected : virtual void Render(sf::RenderTarget& Target) const; public : - PySfRenderWindow *RenderWindow; + PySfRenderTarget *RenderTarget; PyObject *RenderFunction; }; diff --git a/python/src/Font.cpp b/python/src/Font.cpp index c6f49860..1458a0bd 100644 --- a/python/src/Font.cpp +++ b/python/src/Font.cpp @@ -59,27 +59,48 @@ PySfFont_LoadFromFile(PySfFont* self, PyObject *args, PyObject *kwds) const char *kwlist[] = {"Filename", "Charsize", "Charset", NULL}; unsigned int Charsize=30; char *Filename; - char *CharsetTmp = NULL; - int CharsetSize; - bool Result; - - if (! PyArg_ParseTupleAndKeywords(args, kwds, "s|Is#:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &CharsetTmp, &CharsetSize)) - return NULL; - - if (CharsetTmp) + char *Charset=NULL, *EncodingStr; + int Length; + bool result; + std::string Encoding; + if (PyArg_ParseTupleAndKeywords(args, kwds, "s|I:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize)) + result = self->obj->LoadFromFile(Filename, Charsize); + else if (PyArg_ParseTupleAndKeywords(args, kwds, "s|Iu:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &Charset)) { - if ((unsigned char)CharsetTmp[0] == 0xff && (unsigned char)CharsetTmp[1] == 0xfe) - Result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::Text((const sf::Uint16 *)(CharsetTmp+2))); + PyErr_Clear(); +#if Py_UNICODE_SIZE == 4 + result = self->obj->LoadFromFile(Filename, Charsize, (sf::Uint32 *)Charset); +#else + result = self->obj->LoadFromFile(Filename, Charsize, (sf::Uint16 *)Charset); +#endif + } + else if (PyArg_ParseTupleAndKeywords(args, kwds, "s|Is#s:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &Charset, &Length, &EncodingStr)) + { + PyErr_Clear(); + if (EncodingStr == NULL) + result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset)); else - Result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::Text((const sf::Uint8 *)CharsetTmp)); + { + Encoding.assign(EncodingStr); + if (Encoding == "utf8" || Encoding == "") + result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset)); + else if (Encoding == "utf16") + result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF16String((sf::Uint16 *)(Charset+2))); + else if (Encoding == "utf32") + result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF32String((sf::Uint32 *)(Charset+4))); + else + { + PyErr_Format(PyExc_TypeError, "Font.LoadFromFile() Encoding %s not supported", EncodingStr); + return NULL; + } + } } else - Result = self->obj->LoadFromFile(Filename, Charsize); - - if (Result) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + { + PyErr_BadArgument(); + return NULL; + } + return PyBool_FromLong(result); } static PyObject * @@ -88,27 +109,48 @@ PySfFont_LoadFromMemory(PySfFont* self, PyObject *args, PyObject *kwds) const char *kwlist[] = {"Data", "Charsize", "Charset", NULL}; unsigned int Charsize=30, Size; char *Data; - char *CharsetTmp = NULL; - int CharsetSize; - bool Result; - - if (! PyArg_ParseTupleAndKeywords(args, kwds, "s#|Is#:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &CharsetTmp, &CharsetSize)) - return NULL; - - if (CharsetTmp) + char *Charset=NULL, *EncodingStr; + int Length; + bool result; + std::string Encoding; + if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|I:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize)) + result = self->obj->LoadFromMemory(Data, Size, Charsize); + else if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|Iu:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &Charset)) { - if ((unsigned char)CharsetTmp[0] == 0xff && (unsigned char)CharsetTmp[1] == 0xfe) - Result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::Text((const sf::Uint16 *)(CharsetTmp+2))); + PyErr_Clear(); +#if Py_UNICODE_SIZE == 4 + result = self->obj->LoadFromMemory(Data, Size, Charsize, (sf::Uint32 *)Charset); +#else + result = self->obj->LoadFromMemory(Data, Size, Charsize, (sf::Uint16 *)Charset); +#endif + } + else if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|Is#s:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &Charset, &Length, &EncodingStr)) + { + PyErr_Clear(); + if (EncodingStr == NULL) + result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset)); else - Result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::Text((const sf::Uint8 *)CharsetTmp)); + { + Encoding.assign(EncodingStr); + if (Encoding == "utf8") + result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset)); + else if (Encoding == "utf16") + result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF16String((sf::Uint16 *)(Charset+2))); + else if (Encoding == "utf32") + result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF32String((sf::Uint32 *)(Charset+4))); + else + { + PyErr_Format(PyExc_TypeError, "Font.LoadFromMemory() Encoding %s not supported", EncodingStr); + return NULL; + } + } } else - Result = self->obj->LoadFromMemory(Data, Size, Charsize); - - if (Result) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + { + PyErr_BadArgument(); + return NULL; + } + return PyBool_FromLong(result); } static PyObject * @@ -139,16 +181,16 @@ PySfFont_GetGlyph(PySfFont* self, PyObject *args) } static PyMethodDef PySfFont_methods[] = { - {"LoadFromFile", (PyCFunction)PySfFont_LoadFromFile, METH_VARARGS | METH_KEYWORDS, "LoadFromFile(Filename, CharSize, Charset)\n\ + {"LoadFromFile", (PyCFunction)PySfFont_LoadFromFile, METH_VARARGS | METH_KEYWORDS, "LoadFromFile(Filename, CharSize, UnicodeCharset) or LoadFromFile(Filename, CharSize, Charset, Encoding='utf8')\n\ Load the font from a file. Returns True if loading was successful.\n\ Filename : Font file to load\n\ CharSize : Size of characters in bitmap - the bigger, the higher quality (30 by default)\n\ - Charset : Characters set to generate (empty by default - takes the ASCII range [31, 255])"}, - {"LoadFromMemory", (PyCFunction)PySfFont_LoadFromMemory, METH_VARARGS | METH_KEYWORDS, "LoadFromMemory(Data, CharSize, Charset)\n\ + Charset : Characters set to generate (by default, contains the ISO-8859-1 printable characters)"}, + {"LoadFromMemory", (PyCFunction)PySfFont_LoadFromMemory, METH_VARARGS | METH_KEYWORDS, "LoadFromMemory(Data, CharSize, UnicodeCharset) or LoadFromMemory(Data, CharSize, Charset, Encoding='utf8')\n\ Load the font from a file in memory. Returns True if loading was successful.\n\ Data : data to load\n\ CharSize : Size of characters in bitmap - the bigger, the higher quality (30 by default)\n\ - Charset : Characters set to generate (empty by default - takes the ASCII range [31, 255])"}, + Charset : Characters set to generate (by default, contains the ISO-8859-1 printable characters)"}, {"GetDefaultFont", (PyCFunction)PySfFont_GetDefaultFont, METH_NOARGS | METH_STATIC, "GetDefaultFont()\n\ Get the SFML default built-in font (Arial)."}, {"GetCharacterSize", (PyCFunction)PySfFont_GetCharacterSize, METH_NOARGS, "GetCharacterSize()\n\ diff --git a/python/src/RenderTarget.cpp b/python/src/RenderTarget.cpp index 5b2afe24..4953f727 100644 --- a/python/src/RenderTarget.cpp +++ b/python/src/RenderTarget.cpp @@ -33,21 +33,6 @@ extern PyTypeObject PySfColorType; extern PyTypeObject PySfViewType; -static void -PySfRenderTarget_dealloc(PySfRenderTarget *self) -{ - delete self->obj; - free_object(self); -} - -static PyObject * -PySfRenderTarget_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - PySfRenderTarget *self; - self = (PySfRenderTarget *)type->tp_alloc(type, 0); - return (PyObject *)self; -} - static PyObject * PySfRenderTarget_Clear(PySfRenderTarget *self, PyObject *args) { @@ -87,8 +72,7 @@ PySfRenderTarget_GetView(PySfRenderTarget *self) static PyObject * PySfRenderTarget_PreserveOpenGLStates(PySfRenderTarget *self, PyObject *args) { - bool Optimize = PyBool_AsBool(args); - self->obj->PreserveOpenGLStates(Optimize); + self->obj->PreserveOpenGLStates(PyBool_AsBool(args)); Py_RETURN_NONE; } @@ -138,7 +122,7 @@ PyTypeObject PySfRenderTargetType = { "RenderTarget", /*tp_name*/ sizeof(PySfRenderTarget), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfRenderTarget_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -162,16 +146,6 @@ PyTypeObject PySfRenderTargetType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfRenderTarget_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PySfRenderTarget_new, /* tp_new */ }; diff --git a/python/src/RenderWindow.cpp b/python/src/RenderWindow.cpp index 1e486a55..1617c334 100644 --- a/python/src/RenderWindow.cpp +++ b/python/src/RenderWindow.cpp @@ -38,12 +38,8 @@ #include -extern PyTypeObject PySfEventType; extern PyTypeObject PySfViewType; -extern PyTypeObject PySfColorType; extern PyTypeObject PySfWindowType; -extern PyTypeObject PySfWindowSettingsType; -extern PyTypeObject PySfVideoModeType; extern PyTypeObject PySfDrawableType; extern PyTypeObject PySfRenderTargetType; @@ -108,7 +104,9 @@ PySfRenderWindow_DrawObject(PySfRenderWindow *RenderWindow, PySfDrawable *Obj) { if (PyObject_HasAttrString((PyObject *)Obj, "Render")) { - Obj->obj->RenderWindow = RenderWindow; + Py_DECREF(Obj->obj->RenderTarget); + Obj->obj->RenderTarget = (PySfRenderTarget *)RenderWindow; + Py_DECREF(Obj->obj->RenderFunction); Obj->obj->RenderFunction = PyObject_GetAttrString((PyObject *)Obj, "Render"); } RenderWindow->obj->Draw( *(Obj->obj) ); @@ -120,21 +118,18 @@ PySfRenderWindow_DrawObject(PySfRenderWindow *RenderWindow, PySfDrawable *Obj) static PyObject * PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) { - if (!args) + if (args == NULL) return NULL; - - if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)args)) { PyObject *iterator = PyObject_GetIter(args); PyObject *item; - + PyErr_Clear(); if (iterator == NULL) { PyErr_SetString(PyExc_TypeError, "Argument to Draw method is neither a Drawable nor an iterable."); return NULL; } - while ((item = PyIter_Next(iterator))) { if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)item)) @@ -144,16 +139,24 @@ PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) } Py_DECREF(item); } - Py_DECREF(iterator); - - if (PyErr_Occurred()) - return NULL; - } + } + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; +} + +static PyObject * +PySfRenderWindow_PreserveOpenGLStates(PySfRenderWindow *self, PyObject *args) +{ + self->obj->PreserveOpenGLStates(PyBool_AsBool(args)); Py_RETURN_NONE; } static PyMethodDef PySfRenderWindow_methods[] = { + {"PreserveOpenGLStates", (PyCFunction)PySfRenderWindow_PreserveOpenGLStates, METH_O, "PreserveOpenGLStates(Preserve)\n\ +Tell SFML to preserve external OpenGL states, at the expense of more CPU charge. Use this function if you don't want SFML to mess up your own OpenGL states (if any). Don't enable state preservation if not needed, as it will allow SFML to do internal optimizations and improve performances. This parameter is false by default\n\ + Preserve : True to preserve OpenGL states, false to let SFML optimize"}, {"Capture", (PyCFunction)PySfRenderWindow_Capture, METH_NOARGS, "Capture()\n\ Save the content of the window to an image. Returns a sf.Image object."}, {"ConvertCoords", (PyCFunction)PySfRenderWindow_ConvertCoords, METH_VARARGS, "ConvertCoords(WindowX, WindowY, TargetView)\n\ diff --git a/python/src/String.cpp b/python/src/String.cpp index 09b9f8d6..b9551739 100644 --- a/python/src/String.cpp +++ b/python/src/String.cpp @@ -51,19 +51,16 @@ PySfString_new(PyTypeObject *type, PyObject *args, PyObject *kwds) return (PyObject *)self; } - static int PySfString_init(PySfString *self, PyObject *args, PyObject *kwds) { const char *kwlist[] = {"Text", "Font", "Size", NULL}; float Size = 30.f; - std::string Text = ""; - char *TextTmp = NULL; - unsigned int TextSize; + PyObject *Text=NULL; PySfFont *FontTmp = NULL; sf::Font *Font; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "|s#O!f", (char **)kwlist, &TextTmp, &TextSize, &PySfFontType, &FontTmp, &Size)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO!f:String.__init__", (char **)kwlist, &Text, &PySfFontType, &FontTmp, &Size)) return -1; if (FontTmp) @@ -71,39 +68,74 @@ PySfString_init(PySfString *self, PyObject *args, PyObject *kwds) else Font = (sf::Font *)&(sf::Font::GetDefaultFont()); - if (TextSize >= 2 && TextTmp) - if ((unsigned char)TextTmp[0] == 0xff && (unsigned char)TextTmp[1] == 0xfe) + if (Text != NULL) + { + if (PyUnicode_Check(Text)) { - self->obj = new sf::String(sf::Unicode::Text((const sf::Uint16 *)(TextTmp+2)), *Font, Size); - return 0; +#if Py_UNICODE_SIZE == 4 + self->obj = new sf::String((sf::Uint32 *)PyUnicode_AS_UNICODE(Text), *Font, Size); +#else + self->obj = new sf::String((sf::Uint16 *)PyUnicode_AS_UNICODE(Text), *Font, Size); +#endif } - - if (TextTmp != NULL) - self->obj = new sf::String(sf::Unicode::Text((const sf::Uint8 *)(TextTmp)), *Font, Size); +#ifdef IS_PY3K + else if (PyBytes_Check(Text)) + self->obj = new sf::String(sf::Unicode::UTF8String((sf::Uint8 *)PyBytes_AsString(Text)), *Font, Size); +#else + else if (PyString_Check(Text)) + self->obj = new sf::String(sf::Unicode::UTF8String((sf::Uint8 *)PyString_AsString(Text)), *Font, Size); +#endif + else + { + PyErr_SetString(PyExc_TypeError, "String.__init__() first argument must be str"); + return -1; + } + } else - self->obj = new sf::String(); + self->obj = new sf::String("", *Font, Size); return 0; } - - static PyObject * PySfString_SetText(PySfString* self, PyObject *args) { - char *TextTmp = NULL; - int Size; - if (!PyArg_Parse(args, "s#", &TextTmp, &Size)) - return NULL; - - if (Size >= 2) + char *Text, *EncodingStr=NULL; + int Length; + std::string Encoding; + if (PyArg_ParseTuple(args, "u:String.SetText", &Text)) { - if ((unsigned char)TextTmp[0] == 0xff && (unsigned char)TextTmp[1] == 0xfe) +#if Py_UNICODE_SIZE == 4 + self->obj->SetText((sf::Uint32 *)Text); +#else + self->obj->SetText((sf::Uint16 *)Text); +#endif + } + else if (PyArg_ParseTuple(args, "s|#s:String.SetText", &Text, &Length, &EncodingStr)) + { + PyErr_Clear(); + if (EncodingStr == NULL) + self->obj->SetText(sf::Unicode::UTF8String((sf::Uint8 *)Text)); + else { - self->obj->SetText(sf::Unicode::Text((const sf::Uint16 *)(TextTmp+2))); - Py_RETURN_NONE; + Encoding.assign(EncodingStr); + if (Encoding == "utf8") + self->obj->SetText(sf::Unicode::UTF8String((sf::Uint8 *)Text)); + else if (Encoding == "utf16") + self->obj->SetText(sf::Unicode::UTF16String((sf::Uint16 *)(Text+2))); + else if (Encoding == "utf32") + self->obj->SetText(sf::Unicode::UTF32String((sf::Uint32 *)(Text+4))); + else + { + PyErr_Format(PyExc_TypeError, "String.SetText() Encoding %s not supported", EncodingStr); + return NULL; + } } } - self->obj->SetText(sf::Unicode::Text((const sf::Uint8 *)(TextTmp))); + else + { + PyErr_BadArgument(); + return NULL; + } Py_RETURN_NONE; } @@ -146,12 +178,12 @@ PySfString_GetStyle(PySfString* self) static PyObject * PySfString_GetText(PySfString* self) { - std::string Text = (std::string(self->obj->GetText())); -#ifdef IS_PY3K - return PyUnicode_DecodeUTF8(Text.c_str(), (Py_ssize_t)Text.length(), "replace"); +#if Py_UNICODE_SIZE == 4 + sf::Unicode::UTF32String Text(self->obj->GetText()); #else - return PyString_FromString(Text.c_str()); + sf::Unicode::UTF16String Text(self->obj->GetText()); #endif + return PyUnicode_FromUnicode((const Py_UNICODE*)Text.c_str(), Text.length()); } static PyObject * @@ -189,8 +221,8 @@ static PyMethodDef PySfString_methods[] = { {"GetCharacterPos", (PyCFunction)PySfString_GetCharacterPos, METH_O, "GetCharacterPos(Index)\n\ Return the visual position (a tuple of two floats) of the Index-th character of the string, in coordinates relative to the string (note : translation, center, rotation and scale are not applied)\n\ Index : Index of the character"}, - {"SetText", (PyCFunction)PySfString_SetText, METH_O, "SetText(Text)\nSet the text (an utf-8 or utf-16 string).\n Text : New text"}, - {"GetText", (PyCFunction)PySfString_GetText, METH_NOARGS, "GetText()\nGet the text."}, + {"SetText", (PyCFunction)PySfString_SetText, METH_VARARGS, "SetText(UnicodeText) or SetText(Text, Encoding='utf8')\nSet the text. Valid encodings are 'utf8', 'utf16' and 'utf32'.\n Text : New text"}, + {"GetText", (PyCFunction)PySfString_GetText, METH_NOARGS, "GetText()\nGet the text as an unicode string."}, {"SetFont", (PyCFunction)PySfString_SetFont, METH_O, "SetFont(Font)\nSet the font of the string.\n Font : font to use"}, {"GetFont", (PyCFunction)PySfString_GetFont, METH_NOARGS, "GetFont()\nGet the font used by the string."}, {"SetSize", (PyCFunction)PySfString_SetSize, METH_O, "SetSize(Size)\nSet the size of the string.\n Size : New size, in pixels"}, @@ -223,7 +255,7 @@ PyTypeObject PySfStringType = { 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "sf.String defines a graphical 2D text, that can be drawn on screen.\n\ -Default constructor : String ()\nConstruct the string from a utf-8 or a utf-16 string : String(Text, Font=sf.Font.GetDefaultFont(), Size=30.)\n Text : Text assigned to the string\n Font : Font used to draw the string (SFML built-in font by default)\n Size : Characters size (30 by default)", /* tp_doc */ +Default constructor : String ()\nConstruct the string from an unicode or an ascii string : String(Text, Font=sf.Font.GetDefaultFont(), Size=30.)\n Text : Text assigned to the string\n Font : Font used to draw the string (SFML built-in font by default)\n Size : Characters size (30 by default)", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ diff --git a/python/src/Window.cpp b/python/src/Window.cpp index 54da51f4..9844ddf6 100644 --- a/python/src/Window.cpp +++ b/python/src/Window.cpp @@ -287,7 +287,7 @@ Create a window.\n\ Mode : Video mode to use (sf.VideoMode instance)\n\ Title : Title of the window\n\ WindowStyle : Window style (Resize | Close by default)\n\ - Params : Creation parameters (see default constructor for default values)\n"}, + Params : Creation parameters (see default constructor for default values)"}, {"Display", (PyCFunction)PySfWindow_Display, METH_NOARGS, "Display()\nDisplay the window on screen."}, {"EnableKeyRepeat", (PyCFunction)PySfWindow_EnableKeyRepeat, METH_O, "EnableKeyRepeat(Enable)\nEnable or disable automatic key-repeat. Automatic key-repeat is enabled by default.\n Enabled : True to enable, false to disable"}, {"GetEvent", (PyCFunction)PySfWindow_GetEvent, METH_O, "GetEvent(Event)\nGet the event on top of events stack, if any, and pop it. Returns True if an event was returned, False if events stack was empty.\n EventReceived : Event to fill, if any."}, diff --git a/python/src/main.cpp b/python/src/main.cpp index b1d5fefa..9b2a4441 100644 --- a/python/src/main.cpp +++ b/python/src/main.cpp @@ -101,7 +101,7 @@ static PyModuleDef module_def = { module_methods, NULL, NULL, NULL, NULL }; -PyObject * +PyMODINIT_FUNC PyInit_sf(void) #else #define INITERROR return