untested PyColor base implementation

This commit is contained in:
John McCardle 2024-03-23 23:07:10 -04:00
parent 3728e5fcc8
commit 2cac6f03c6
2 changed files with 82 additions and 0 deletions

42
src/PyColor.cpp Normal file
View File

@ -0,0 +1,42 @@
#include "PyColor.h"
PyColor::PyColor()
{
}
PyObject* PyTexture::pyObject()
{
PyObject* obj = PyType_GenericAlloc(&mcrfpydef::PyColorType, 0);
try {
((PyTextureObject*)obj)->data = shared_from_this();
}
catch (std::bad_weak_ptr& e)
{
std::cout << "Bad weak ptr: shared_from_this() failed in PyTexture::pyObject(); did you create a PyTexture outside of std::make_shared? enjoy your segfault, soon!" << std::endl;
}
// TODO - shared_from_this will raise an exception if the object does not have a shared pointer. Constructor should be made private; write a factory function
return obj;
}
Py_hash_t PyTexture::hash(PyObject* obj)
{
auto self = (PyTextureObject*)obj;
return reinterpret_cast<Py_hash_t>(self->data.get());
}
int PyTexture::init(PyTextureObject* self, PyObject* args, PyObject* kwds)
{
static const char* keywords[] = { "filename", "sprite_width", "sprite_height", nullptr };
char* filename;
int sprite_width, sprite_height;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "sii", const_cast<char**>(keywords), &filename, &sprite_width, &sprite_height))
return -1;
self->data = std::make_shared<PyTexture>(filename, sprite_width, sprite_height);
return 0;
}
PyObject* PyTexture::pynew(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
return (PyObject*)type->tp_alloc(type, 0);
}

40
src/PyColor.h Normal file
View File

@ -0,0 +1,40 @@
#pragma once
#include "Common.h"
#include "Python.h"
class PyColor;
typedef struct {
sf::Color* target; // color target to set/get
std::weak_ptr<UIDrawable> parent; // lifetime management: parent must still exist
int index; // specific to the parent class, which color is it?
} _PyColorData;
typedef struct {
PyObject_HEAD
_PyColorData data;
} PyTextureObject;
class PyColor
{
private:
_PyColorData data;
public:
PyObject* pyObject();
static Py_hash_t hash(PyObject*);
static int init(PyColorObject*, PyObject*, PyObject*);
static PyObject* pynew(PyTypeObject* type, PyObject* args=NULL, PyObject* kwds=NULL);
};
namespace mcrfpydef {
static PyTypeObject PyColorType = {
.tp_name = "mcrfpy.Color",
.tp_basicsize = sizeof(PyColorObject),
.tp_itemsize = 0,
.tp_hash = PyColor::hash,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = PyDoc_STR("SFML Color Object"),
.tp_init = (initproc)PyColor::init,
.tp_new = PyTColor::pynew,
};
}