repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
PancakeSoftware/openHabAI | catflow/cpp/include/server/ApiSeasocksServer.h | <gh_stars>1-10
/*
* File: ApiSeasocksServer
*/
#ifndef OPENHABAI_APISEASOCKSSERVER_H
#define OPENHABAI_APISEASOCKSSERVER_H
#include <Catflow.h>
#include "ApiServer.h"
#ifdef USE_SEASOCKS
#include <seasocks/Server.h>
#include <seasocks/PrintfLogger.h>
/**
* identifier for client who send a request
*/
class SeasocksClient: public Client {
public:
WebSocket* websocket = nullptr;
SeasocksClient(WebSocket* webSocket) {
this->websocket = webSocket;
}
WebSocket* getWebsocket() const {
return websocket;
}
string toString() {
if (websocket != nullptr)
return string(inet_ntoa(websocket->getRemoteAddress().sin_addr)) + ":" + to_string(websocket->getRemoteAddress().sin_port);
else
return "??";
}
bool operator<(const Client &other) const {
const SeasocksClient *oth = dynamic_cast<const SeasocksClient*>(&other);
if (oth != nullptr)
return websocket < oth->websocket;
return false;
}
};
/**
* own logger for seaSocks
*/
class SeasocksLogger : public seasocks::Logger {
public:
SeasocksLogger(string name, Level _minLevelToLog = Level::DEBUG)
: Logger(),
minLevelToLog(_minLevelToLog)
{
l.setLogName(name);
}
~SeasocksLogger() = default;
virtual void log(Level level, const char* message) {
if (level >= minLevelToLog)
{
if (level == Level::DEBUG)
l.debug(message);
if (level == Level::INFO)
l.info(message);
if (level == Level::ACCESS)
l.info("ACCESS: " + string(message));
if (level == Level::WARNING)
l.warn(message);
if (level == Level::ERROR)
l.err(message);
if (level == Level::SEVERE)
l.info("SEVERE: " + string(message));
}
}
Level minLevelToLog;
Log l;
};
class ApiSeasocksServer: public ApiServer
{
public:
ApiSeasocksServer()
: serverWebsocket(make_shared<SeasocksLogger>("SeasocksServer", Logger::Level::INFO)) {
setLogName("SeasocksServer");
}
void start() override
{
// start server threads
thread serverWebsocketThread(serverWebsocketThreadFunction, this);
serverWebsocketThread.detach();
ok("created serverWebsocket thread");
}
void startBlocking() override
{
ok("will start serverWebsocket blocking");
serverWebsocketThreadFunction(this);
}
void send(Json packet, Client &destination, PacketIdentifier &packetIdentifier) override
{
SeasocksClient *dest = dynamic_cast<SeasocksClient*>((Client*)&destination);
serverWebsocket.execute([=]() mutable {
dest->websocket->send(packet.dump());
packetIdentifier.sendDone();
});
}
void sendBroadcast(Json packet) override
{
serverWebsocket.execute([=]() {
for (auto s : webSockConnections)
s.first->send(packet.dump());
});
}
static void serverWebsocketThreadFunction(ApiSeasocksServer *s)
{
s->serverWebsocket.addWebSocketHandler("/", make_shared<WebSocketHandler>(s));
s->ok("listen for webSocket connection on port " + to_string(Catflow::port));
s->serverWebsocket.serve("", Catflow::port);
s->info("stop listening to webSocket on port " + to_string(Catflow::port) + " [stopped serverWebsocketThread]");
}
private:
Server serverWebsocket;
map<WebSocket *, SeasocksClient *> webSockConnections;
struct WebSocketHandler : WebSocket::Handler
{
ApiSeasocksServer *server;
WebSocketHandler(ApiSeasocksServer *server) {
this->server = server;
}
void onConnect(WebSocket *socket) override {
SeasocksClient *client = new SeasocksClient(socket);
server->webSockConnections.emplace(socket, client);
Catflow::onClientConnect(*client);
}
void onData(WebSocket *webSocket, const char *data) override {
auto client = server->webSockConnections.find(webSocket);
Catflow::onData(*client->second, string(data));
}
void onDisconnect(WebSocket *socket) override {
auto client = server->webSockConnections.find(socket);
Catflow::onClientDisconnect(*client->second);
server->webSockConnections.erase(client);
delete client->second;
}
};
};
#endif
#endif //OPENHABAI_APISEASOCKSSERVER_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/ApiSubscribable.h | <filename>catflow/cpp/include/ApiSubscribable.h<gh_stars>1-10
/*
* File: ApiSubscribable.h
*
*/
#ifndef OPENHABAI_APISUBSCRIBABLE_H
#define OPENHABAI_APISUBSCRIBABLE_H
#include <util/Log.h>
#include <Catflow.h>
#include "ApiProcessible.h"
/**
* provides api command: 'subscribe' and 'unsubscribe'
* @warning do not create object of this class before the main function, because the ApiSubscribable constructor calls a static function of Catflow (its static members have to be constructed before)
*/
class ApiSubscribable: public virtual ApiProcessible
{
public:
ApiSubscribable();
~ApiSubscribable() {
Catflow::unRegisterClientList(this->subscribers);
}
ApiRespond *processApi(ApiRequest request) override;
/**
* send api message to each subscriber
* @param request
*/
void sendToSubscribers(ApiRequest request);
/**
* send api message to each subscriber
* @param request
* @param skipSendUpdateTo not send update to this client
*/
void sendToSubscribers(ApiRequest request, Client &skipSendUpdateTo);
protected:
set<Client*> subscribers;
static Log l;
};
#endif //OPENHABAI_APISUBSCRIBABLE_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/Util.h | <gh_stars>1-10
/*
* File: Util
* Author: <NAME>
*
*/
#ifndef OPENHABAI_CATFLOW_UTIL_H
#define OPENHABAI_CATFLOW_UTIL_H
#include <exception>
#include <string>
class JsonObjectException: public std::exception {
private:
std::string message;
public:
explicit JsonObjectException(const std::string& message) : message(message) {}
virtual const char* what() const throw() {
return message.c_str();
}
};
#endif //OPENHABAI_CATFLOW_UTIL_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/Catflow.h | /*
* Catflow.h
*/
#ifndef CATFLOW_H
#define CATFLOW_H
#include <thread>
#include <json.hpp>
#include <util/Log.h>
#include <ApiMessage.h>
#include <queue>
#include "ApiProcessible.h"
#include <server/ApiServer.h>
#include <set>
using namespace std;
using Json = nlohmann::json;
class Catflow
{
public:
/**
* start catflow
* @param port listen for incoming api connections at this port
* @param httpServerPath path to http root dir to serve
*/
template <class SERVER>
static void start(int port, string httpServerPath = "") {
if (Catflow::apiRoot == nullptr)
l.warn("you have to set apiRoute!");
Catflow::port = port;
Catflow::httpServerPath = httpServerPath;
// create server
server = new SERVER();
// connect
server->start();
}
/**
* set api root object
* @note do this before calling start()
* @param apiRoot
*/
static void setApiRootRoute(ApiProcessible &apiRoot){
Catflow::apiRoot = &apiRoot;
}
static void sendData(Json data);
static void send(ApiRespond message);
static void send(ApiRequest message);
static void send(ApiRespond message, Client &destination);
static void send(ApiRequest message, Client &destination);
static void onClientConnect(Client &client);
static void onClientDisconnect(Client &client);
static void onData(Client &sender, string data);
/**
* @param list always is subset of connected websockets
*/
static void registerClientList(set<Client*> &list);
static void unRegisterClientList(set<Client*> &list);
/**
* @deprecated use Chart from Chart.h
* chart
*/
class Chart
{
public:
Chart(string name);
Chart &setGraphData(string graph, vector<float> xVals, vector<float> yVals);
Chart &setGraphData(string graph, initializer_list<float> xVals, initializer_list<float> yVals);
void changeApply(); // send and update chart
void addApply(); // send and add to chart
private:
void apply(string type);
Json tmpGraphs;
string name;
};
static Chart &getChart(string name);
/* track packages to send, for testing
* pair<destination for message, message>
*/
static list<pair<Client*, ApiRequest>> requestsToSend;
static list<pair<Client*, ApiRespond>> responsesToSend;
static int port;
static string httpServerPath;
private:
static ApiProcessible* apiRoot;
static ApiServer* server;
static Log l;
static set<Client *> webSockConnections;
static set<set<Client*>*> linkedWebSockConnections;
};
struct PacketIdentifier {
virtual void sendDone() {};
};
template <typename T>
struct PacketIdentifierT: public PacketIdentifier {
T packId;
PacketIdentifierT(T packId) {
this->packId = packId;
}
virtual void sendDone() {}
};
template <>
struct PacketIdentifierT<list<pair<Client*, ApiRespond>>::const_iterator>: public PacketIdentifier
{
list<pair<Client*, ApiRespond>>::const_iterator packId;
PacketIdentifierT(list<pair<Client*, ApiRespond>>::const_iterator packId) {
this->packId = packId;
}
void sendDone() {
Catflow::responsesToSend.erase(packId);
}
};
template <>
struct PacketIdentifierT<list<pair<Client*, ApiRequest>>::const_iterator>: public PacketIdentifier {
list<pair<Client*, ApiRequest>>::const_iterator packId;
PacketIdentifierT(list<pair<Client*, ApiRequest>>::const_iterator packId) {
this->packId = packId;
}
void sendDone() {
Catflow::requestsToSend.erase(packId);
}
};
#endif //CATFLOW_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/server/ApiuWebsocketsServer.h | <reponame>PancakeSoftware/openHabAI<filename>catflow/cpp/include/server/ApiuWebsocketsServer.h
/*
* File: ApiSeasocksServer
*/
#ifndef OPENHABAI_APISUWEBSOCKETSSERVER_H
#define OPENHABAI_APISUWEBSOCKETSSERVER_H
#include "../Catflow.h"
#include "ApiServer.h"
#include <uWS.h>
#include <thread>
#include <boost/filesystem.hpp>
/**
* identifier for client who send a request
*/
class UWebsocketsClient: public Client {
public:
uWS::WebSocket<uWS::SERVER>* websocket = nullptr;
UWebsocketsClient(uWS::WebSocket<uWS::SERVER>* webSocket) {
this->websocket = webSocket;
}
uWS::WebSocket<uWS::SERVER>* getWebsocket() const {
return websocket;
}
string toString() {
if (websocket != nullptr)
return string(websocket->getAddress().address) + " :" + to_string(websocket->getAddress().port);
else
return "??";
}
bool operator<(const Client &other) const {
const UWebsocketsClient *oth = dynamic_cast<const UWebsocketsClient*>(&other);
if (oth != nullptr)
return websocket < oth->websocket;
return false;
}
};
class ApiuWebsocketsServer: public ApiServer
{
public:
ApiuWebsocketsServer()
{
setLogName("uWebsocketServer");
// set callbacks
hub.onMessage([this](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) {
auto client = webSockConnections.find(ws);
Catflow::onData(*client->second, string(message).substr(0, length));
});
hub.onConnection([this](uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest request){
UWebsocketsClient *client = new UWebsocketsClient(ws);
webSockConnections.emplace(ws, client);
Catflow::onClientConnect(*client);
});
hub.onDisconnection([this](uWS::WebSocket<uWS::SERVER> *ws, int code, char *message, size_t length){
auto client = webSockConnections.find(ws);
Catflow::onClientDisconnect(*client->second);
webSockConnections.erase(client);
delete client->second;
});
// http
if (Catflow::httpServerPath != "")
hub.onHttpRequest([this](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) {
// on Http request
auto doc = webDocs.find(req.getUrl().toString());
if (doc != webDocs.end())
res->end(doc->second.data(), doc->second.size());
else {
trace("got http request for " + req.getUrl().toString() + " -> redirect to index.html ");
doc = webDocs.find("/index.html");
if (doc != webDocs.end())
res->end(doc->second.data(), doc->second.size());
else {
string s = "can't find index.html :(";
res->end(s.data(), s.size());
}
}
});
hub.onError([this](int type){
err("err on port " + to_string(type));
});
}
void start() override
{
// start server threads
serverThread = new thread([this](){
if (hub.listen(Catflow::port)) {
// run is blocking
ok("listen for webSocket/http connection on port " + to_string(Catflow::port));
// cache web files
if (Catflow::httpServerPath.size() > 0) {
int filesAmount = 0;
int filesTotalSize = 0;
try
{
auto path = boost::filesystem::path(Catflow::httpServerPath);
int cutFromPath = (Catflow::httpServerPath.back() == '/') ? path.size()-1 : path.size();
for (boost::filesystem::recursive_directory_iterator i(path), end; i != end; ++i)
{
if (!is_directory(i->path())) {
string webDocPath = i->path().string().substr(cutFromPath, i->path().size() - cutFromPath);
boost::filesystem::ifstream infile{i->path()};
string str{istreambuf_iterator<char>(infile), istreambuf_iterator<char>()};
webDocs.emplace(webDocPath, str);
filesTotalSize+= str.size();
filesAmount++;
// trace("cached file: " + webDocPath);
}
}
} catch (std::exception &e) {
err("can't read cache web files: " + string(e.what()));
}
info("cached " + to_string(filesAmount) + " files ("+ to_string((float)filesTotalSize/(1024*1024)) +" Mbyte) from webserver root '" + Catflow::httpServerPath +"'");
}
hub.run();
} else {
fatal("listen for webSocket/http connection on port " + to_string(Catflow::port));
}
});
ok("created serverWebsocket thread");
}
void startBlocking() override
{
ok("will start serverWebsocket blocking");
if (hub.listen(Catflow::port)) {
// run is blocking
ok("listen for webSocket connection on port " + to_string(Catflow::port));
hub.run();
} else {
}
}
void send(Json packet, Client &destination, PacketIdentifier &packetIdentifier) override
{
UWebsocketsClient *dest = dynamic_cast<UWebsocketsClient*>((Client*)&destination);
string msg = packet.dump();
dest->websocket->send(msg.data(), msg.size(), uWS::TEXT);
packetIdentifier.sendDone();
}
void sendBroadcast(Json packet) override
{
for (auto s : webSockConnections) {
string msg = packet.dump();
s.first->send(msg.data(), msg.size(), uWS::TEXT);
}
}
private:
uWS::Hub hub;
thread *serverThread;
map<uWS::WebSocket<uWS::SERVER> *, UWebsocketsClient *> webSockConnections;
map<string, string> webDocs;
};
#endif //OPENHABAI_APISUWEBSOCKETSSERVER_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/JsonList.h | <reponame>PancakeSoftware/openHabAI<filename>catflow/cpp/include/JsonList.h<gh_stars>1-10
/*
* File: JsonList.h
* Author: <NAME>
*
*/
#ifndef OPENHABAI_JSONLIST_H
#define OPENHABAI_JSONLIST_H
#include <json.hpp>
#include <string>
#include <list>
#include <boost/static_assert.hpp>
#include "ApiJsonObject.h"
#include "ApiMessage.h"
#include "ApiProcessible.h"
using Json = nlohmann::json;
using namespace std;
class __JsonList {};
template<class T>
/**
* JsonList class
* elements updatable via json (get, getAll, create)
* @param T extends JsonObject
* @note if derived objects of T are inserted into JsonList, T needs a virtual destructor because on destruction JsonList also deletes all its items
*/
class JsonList : public ApiJsonObject, public __JsonList
{
BOOST_STATIC_ASSERT_MSG(is_base_of<ApiProcessible, T>::value, "JsonList<T> T has to be derivative of ApiProcessible to provide necessary functionality"); // @TODO list for every type
public:
string folder;
int defaultIdAutoIncrement = 0;
JsonList();
JsonList(int &idAutoIncrement);
~JsonList();
/**
* progress ApiRequest, will forward request to children if necessary
* @param request.route defines something similar to rest url, in this example you want to access
* @param request.what defines action to perform, allowed values depend on route
* @param request.data contains data that is necessary to perform action
*/
virtual ApiRespond* processApi(ApiRequest request);
/**
* get by id
* @param id
* @return NULL if not found
*/
T &get(int id);
/**
* replace element at id in list, it is created if not exists
* @note element is copied into list
* @param id
* @param element
*/
void set(int id, T element);
/**
* add element to list, id is set automatic
* @param element
*/
void add(T element);
/**
* remove element at index i, element is deleted too
* @param id
* @return
*/
bool remove(int id);
/**
* @return amount of items in list
*/
int length();
/**
* items list
* @param first id
* @param second T
*/
map<int, T *> items;
/**
* set function to create item instance
* @param createItemFunc
*/
void setCreateItemFunction(function<T *(Json params)> createItemFunc);
void restore() override;
void store() override;
void remove() override;
void setRoute(ApiMessageRoute route) override;
void params() override
{ JsonObject::params();
paramWithFunction("length",
[this] (Json val) {throw JsonObjectException("can't set length of list");},
[this] () { return items.size(); });
}
private:
int &idAutoIncrement;
function<T *(Json params)> createItemFunc = [](Json params) -> T *
{
auto *t = new T();
return t;
};
};
#include "../source/JsonList.tpp"
#endif //OPENHABAI_JSONLIST_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/ApiJsonObject.h | /*
* File: ApiJsonObject.h
* Author: <NAME>
*/
#ifndef OPENHABAI_APIJSONOBJECT_H
#define OPENHABAI_APIJSONOBJECT_H
#include <stdlib.h>
using namespace std;
#include <util/Log.h>
#include <json.hpp>
#include <string>
#include <list>
#include <memory>
#include <boost/any.hpp>
#include <unordered_map>
#include "ApiProcessible.h"
#include "Util.h"
#include "ApiSubscribable.h"
#include <stdarg.h>
#include "JsonObject.h"
/*
* JsonObject class
* bind variables to json keys
* supported data types: int, float, double, bool
*/
class ApiJsonObject : protected virtual Log, public virtual ApiSubscribable, public virtual JsonObject
{
public:
ApiJsonObject();
ApiJsonObject(Json params);
/**
* set configured class attributes to values in params
* , save changes and send updates to subscribers
* @see JsonObject::params()
* @return vector of changed param names
*/
vector<string> fromJson(Json params, bool catchParameterErrors = false) override;
/**
* set configured class attributes to values in params
* , save changes and send updates to subscribers
* @param skipSendUpdateTo not send update to this client
* @see JsonObject::params()
* @return vector of changed param names
*/
vector<string> fromJson(Json params, Client &skipSendUpdateTo);
/**
* store toJson output in file
* @param path
* @param fileName
* @return true if successful
*/
virtual bool save(string path, string fileName);
/**
* load json from file and apply to object
* @param path
* @param fileName
* @return true if successful
*/
virtual bool load(string path, string fileName);
/**
* send changed object params to all subscribers
* @param param... changed json object params
*/
void notifyParamsChanged(vector<string> param);
//void notifyParamsChanged(string param, ...);
ApiRespond *processApi(ApiRequest request) override;
void restore() override;
void store() override;
void remove() override;
void storeMe() override;
void setRoute(ApiMessageRoute route) override;
private:
template <typename T>
vector<T> flatten(T t)
{
vector<T> v;
v.push_back(t);
return v;
}
template<typename T, typename... Args>
vector<T> flatten(T t, Args... args) // recursive variadic function
{
vector<T> v = {t};
vector<T> before = flatten(args...);
v.insert(before.begin(), before.end());
return v;
}
};
/**
* helper
*/
#endif // OPENHABAI_APIJSONOBJECT_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/Chart.h | /*
* File: Chart.h
* Author: <NAME>
*
*/
#ifndef OPENHABAI_CHART_H
#define OPENHABAI_CHART_H
#include <util/util.h>
#include "ApiJsonObject.h"
#include "Catflow.h"
class RangeParam;
class ValueParam;
class ChartDataPoint;
class ChartDataPointSimple;
/*
* Chart class
*/
class Chart: public ApiJsonObject
{
public:
Chart();
/*
* Json keys */
void params() override { ApiJsonObject::params();
paramReadOnly("inputNames", inputNames);
paramReadOnly("outputNames", outputNames);
}
/**
* set input/output names and their Id
* @param inputNames
* @param outputNames
*/
void setInputOutputNames(map<int, string> inputNames, map<int, string> outputNames) {
this->inputNames = inputNames;
this->outputNames = outputNames;
}
void setInputNames(map<int, string> inputNames) {
this->inputNames = inputNames;
}
void setOutputNames(map<int, string> outputNames) {
this->outputNames = outputNames;
}
/**
* set input/output names, id is set automatic
* @param inputNames
* @param outputNames
*/
void setInputOutputNames(vector<string> inputNames, vector<string> outputNames) {
this->inputNames.clear();
this->outputNames.clear();
int i = 0;
for (string name : inputNames)
this->inputNames.emplace(i++, name);
i = 0;
for (string name : outputNames)
this->outputNames.emplace(i++, name);
}
ApiRespond *processApi(ApiRequest request) override;
/**
* send change data to subscribers
*/
void pushUpdate();
protected:
map<int, string> inputNames;
map<int, string> outputNames;
};
/*
* chart for multidimensional data
* all is updated
*/
class ParameterChart: public Chart
{
public:
ParameterChart();
/*
* Json keys */
void params() override { Chart::params();
param("fixedInputs", fixedInputs);
param("rangeInputs", rangeInputs);
param("outputs", outputs);
}
/**
* set the function for generating chart data
* @param func generates for given inputValue( map<inputID, value> ) outputValue( map<outputID, value> )
*/
void setUpdateFunction(function<map<int, float> (const map<int, float> &inputValues, const vector<int> &outputIds)> func) {
this->updateFunc = func;
}
/**
* set the function for generating chart data
* @param func returns outputValues( map<outputID, value> ) by given ranges
* @note input and outputId represented by index
*/
void setUpdateFunctionRanged(function<map<int, vector<ChartDataPoint>> (const vector<RangeParam> &inputRanges, vector<ValueParam> &fixedInputs, const vector<int> &outputIds)> func) {
this->updateFuncRanged = func;
}
/**
* execute update function
* @note blocking
*/
void recalcData();
ApiRespond *processApi(ApiRequest request) override;
private:
vector<ValueParam> fixedInputs;
vector<RangeParam> rangeInputs;
vector<int> outputs;
map<int, vector<ChartDataPoint>> data;
function<map<int, float> (const map<int, float> &inputValue, const vector<int> &outputIds)> updateFunc{nullptr};
function<map<int, vector<ChartDataPoint>> (const vector<RangeParam> &inputRanges, vector<ValueParam> &fixedInputs, const vector<int> &outputIds)> updateFuncRanged{nullptr};
};
/*
* chart for 2D data
* x-axis =
* add dataPoints over time
*/
class SeriesChart: public Chart
{
public:
SeriesChart();
/**
* add dataPoint to chart
* @param outputId
* @param inputValues
* @param outputValue
*/
void addDataPoint(int outputId, vector<float> inputValues, float outputValue);
/**
* add dataPoint to chart
* @param outputName
* @param inputValues
* @param outputValue
*/
void addDataPoint(string outputName, vector<float> inputValues, float outputValue);;
/**
* delete all data form chart
*/
void clearData();
protected:
map<int, vector<ChartDataPointSimple>> data;
};
class ChartDataPoint: public JsonObject{
public:
float value;
map<int, float> inputs;
ChartDataPoint(float value, map<int, float> inputs) : value(value), inputs(inputs) {}
ChartDataPoint(float value, vector<float> inputsVec) : value(value), inputs() {
int i=0;
for (auto input = inputsVec.begin(); input != inputsVec.end(); input++) {
inputs.emplace(i, *input);
i++;
}
}
void params() override {
param("value", value);
paramReadOnly("inputs", inputs);
}
};
class ChartDataPointSimple: public JsonObject{
public:
float value;
vector<float> inputs;
ChartDataPointSimple(float value, vector<float> inputs) : value(value), inputs(inputs) {}
void params() override {
param("value", value);
paramReadOnly("inputs", inputs);
}
};
#endif //OPENHABAI_CHART_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/util/Log.h | /*
* File: Log.h
* Author: <NAME>
*
*/
#ifndef OPENHABAI_LOG_H
#define OPENHABAI_LOG_H
// include
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
using namespace std;
/*
* Log class
*/
class Log
{
public:
Log();
Log(string nameShort);
static void setLogLevel(char log_level_mask);
static void setLogMask(char log_mask);
static void setUseLongLogNames(bool use);
static void setUseColor(bool use);
void setLogName(string nameShort); // set log name example: class name
void setLogName(string nameShort, string nameLong); // set log name example: class name
void fatal(string text); // error message
void fatal(string text, string error); // error message
void err(string text); // error message
void err(string text, string error); // error message
void warn(string text); // warning message
void ok(string text); // ok message
void debug(string text);// debug message
void info(string text) const; // information message
void trace(string text);// trace info message
void outErr(string text, bool error, string errorText); // ok/err - print error if error=true
void outErr(string text, bool error); // ok/err - print error if error=true
void outFat(string text, bool error, string errorText); // ok/fatal - print error if error=true
void outFat(string text, bool error); // ok/fatal - print error if error=true
static const char
LOG_LEVEL_FATAL = 0b00000000,
LOG_LEVEL_ERROR = 0b00000001,
LOG_LEVEL_WARNING = 0b00000010,
LOG_LEVEL_OK = 0b00000100,
LOG_LEVEL_DEBUG = 0b00001000,
LOG_LEVEL_INFORMATION = 0b00010000,
LOG_LEVEL_TRACE = 0b00100000,
LOG_LEVEL_ALL = 0b11111111;
private:
string logNameShort, logNameLong;
static int logNameShortLongest;
static char logLevelMask;
static bool useLongLogNames, useColors;
static int maxNameLongLen;
void print(string tag, string text, char tagMask) const;
};
#endif //OPENHABAI_LOG_H
|
PancakeSoftware/openHabAI | trainServer/source/include/SelectorView.h | //
// Created by <NAME> on 07.06.18.
//
#ifndef OPENHABAI_SELECTORVIEW_H
#define OPENHABAI_SELECTORVIEW_H
#include <stdlib.h>
#include <ApiJsonObject.h>
using namespace std;
class SelectorView : public ApiJsonObject
{
public:
vector<string> options;
SelectorView() = default;
SelectorView(vector<string> options) :
options(options),
optionsValue(options.size())
{
// Is already set somewhere (implemented for radio buttons)
bool hasValue = false;
for (bool b : optionsValue)
hasValue |= b;
// First option is selected
if (optionsValue.size() > 0 && !hasValue)
optionsValue[0] = true;
}
void params() override
{
ApiJsonObject::params();
param("options", options);
param("optionValues", optionsValue).onChanged([this] () {
if (onChange != nullptr)
onChange(optionsValue, optionsValue);
});
}
/**
* A function to trigger a on change function for the selection view
* @param onChange.values True on every selected value
* @param onChange.changeValues True on every changed index of options
*/
void onSelectionChange(function<void(vector<bool> values, vector<bool> changedValues)> onChange)
{
this->onChange = onChange;
}
vector<bool> getCurrentValues()
{
return optionsValue;
}
private:
vector<bool> optionsValue;
function<void(vector<bool>, vector<bool>)> onChange = nullptr;
};
#endif //OPENHABAI_SELECTORVIEW_H
|
PancakeSoftware/openHabAI | trainServer/source/include/ApiRoot.h | /*
* File: ApiRoot.h
* Author: <NAME>
*
*/
#ifndef APIROOT_H
#define APIROOT_H
#include <json.hpp>
#include <ApiRoute.h>
#include <dataStructures/DataStructure.h>
#include "Catflow.h"
#include "Settings.h"
using namespace std;
using Json = nlohmann::json;
class DataStructure;
/*
* ApiRoot class
* holds dataStructures List
*/
class ApiRoot: public ApiRoute
{
public:
JsonList<DataStructure> datastructures{};
Settings settings{};
ApiRoot()
{
setSubRoutes({
{"dataStructures", &datastructures},
{"settings", &settings}
});
datastructures.setCreateItemFunction(DataStructure::create);
}
};
#endif //APIROOT_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/ApiRoute.h | /*
* File: ApiRoute.h
* Author: <NAME>
*
*/
#ifndef OPENHABAI_APIROUTE_H
#define OPENHABAI_APIROUTE_H
#include <json.hpp>
#include <string>
#include <list>
#include <ApiMessage.h>
#include <util/Log.h>
#include <boost/optional.hpp>
#include <JsonList.h>
#include <ApiJsonObject.h>
#include <ApiProcessible.h>
using Json = nlohmann::json;
using namespace std;
/*
* ApiRoute class
* represents one route object in route list
* expl.: here {"Component-A": "entityID-A"}
* "route": [
* {"Component-A": "entityID-A"},
* {"Sub-Component": "entityID-B"},
* ]
*/
class ApiRoute : public virtual ApiProcessible, protected virtual Log
{
public:
ApiRoute();
/**
* @deprecated
* @warning this crashes if object that is inserted into routes in not fully constructed
* @note use setSubRoutes() instead
* @param subRoutes set 'static' sub routes
* @see setSubRoutes(vector<ApiRoute*>& routes)
*/
ApiRoute(map<string, ApiProcessible*> subRoutes);
/**
* progress first route-object in route list
* @param route route list, defines something similar to rest url, in this example you want to access
* @param what defines action to perform, allowed values depend on route
* @param data contains data that is necessary to perform action
*/
virtual ApiRespond* processApi(ApiRequest request);
/**
* set 'static' sub routes
* @param routes pair.first = the ApiRoute object,
* pair.second = name of route
*/
void setSubRoutes(map<string, ApiProcessible*> routes);
void restore() override;
void store() override;
void remove() override;
void setRoute(ApiMessageRoute route) override;
private:
map<string, ApiProcessible*> routes;
};
class ApiJsonObject;
class ApiRouteJson: public ApiRoute, public ApiJsonObject
{
public:
ApiRouteJson() : ApiRoute(){}
/**
* @deprecated
* @warning this crashes if object that is inserted into routes in not fully constructed
* @note use setSubRoutes() instead
* @param subRoutes set 'static' sub routes
* @see setSubRoutes(vector<ApiRoute*>& routes)
*/
ApiRouteJson(map<string, ApiProcessible*> subRoutes) : ApiRoute(subRoutes) {}
ApiRespond *processApi(ApiRequest request) override
{
auto resp = ApiRoute::processApi(request);
if (resp == nullptr && request.route.isEmpty()) // for me
return ApiJsonObject::processApi(request);
else
return resp;
}
void restore() override
{
ApiJsonObject::restore();
ApiRoute::restore();
}
void store() override
{
ApiJsonObject::store();
ApiRoute::store();
}
void storeMe() override
{
ApiJsonObject::storeMe();
}
void remove() override
{
ApiRoute::remove();
ApiJsonObject::remove();
}
void setRoute(ApiMessageRoute route) override
{
ApiJsonObject::setRoute(route);
ApiRoute::setRoute(route);
}
};
#endif //OPENHABAI_APIROUTE_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/ApiProcessible.h | <gh_stars>1-10
/*
* File: ApiProcessible.h
* Author: <NAME>
*
*/
#ifndef OPENHABAI_APIPROCESSIBLE_H
#define OPENHABAI_APIPROCESSIBLE_H
#include <json.hpp>
#include <string>
#include <list>
#include "ApiMessage.h"
#include <boost/optional.hpp>
using Json = nlohmann::json;
using namespace std;
/*
* Apiprocessible class
* object than is able to process api requests
* -> via processApi
*/
class ApiProcessible
{
public:
/**
* progress ApiRequest, will forward request to children if necessary
* @param request.route defines something similar to rest url, in this example you want to access
* @param request.what defines action to perform, allowed values depend on route
* @param request.data contains data that is necessary to perform action
*/
virtual ApiRespond* processApi(ApiRequest request)
{
auto el = processWhats.find(request.what);
if (el != processWhats.end())
return el->second(request);
return nullptr;
};
/**
* restore saved state of self and subObjects
*/
virtual void restore() {};
/**
* store state of self and subObjects
*/
virtual void store() {};
/**
* removes all persistent saved data of this object and subObjects
*/
virtual void remove() {};
/**
* store state of self
* @TODO merge with store()
*/
virtual void storeMe() {};
/*
* set full path to store this
* this calls setStorePath of subObject recursively
* example: /students/0/courses/0
*/
virtual void setRoute(ApiMessageRoute route)
{
this->route = route;
routeString = route.toString();
}
/**
* set full path to store this and defines routes of all children
* @example ./my/file/path/to/store/root/of/api/
* @param path has to end with '/'
*/
virtual void setStorePath(const string path) {
ApiMessageRoute myRoute;
myRoute.pathPrefix = path;
this->setRoute(myRoute);
}
protected:
boost::optional<ApiMessageRoute> route;
string routeString;
void addAction(string what, function<ApiRespond *(ApiRequest request)> action)
{processWhats.insert({what, action});};
private:
map<string, function<ApiRespond*(ApiRequest request)>> processWhats;
};
/*
* from and to json for RoutePath
*/
/*
using nlohmann::json;
void to_json(json& j, const RoutePath& p) {
j = Json{};
for (auto item : p)
j.push_back({{item.first, item.second}});
}*/
/*
void from_json(const Json& j, RoutePath& p) {
for (auto item : j)
p.push_back({item.begin().key(), item.begin().value()});
}
*/
#endif //OPENHABAI_APIPROCESSIBLE_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/util/Filesystem.h | <reponame>PancakeSoftware/openHabAI
/*
* File: Filesystem.h
* Author: <NAME>
*
*/
#ifndef FILESYSTEM_H
#define FILESYSTEM_H
#include <string>
#include <functional>
using namespace std;
/*
* Filesystem
*/
namespace Filesystem
{
bool lsFor(string path, function<void (string, bool)> onEntry); // list contend of folder, call onEntry function
bool createDirIfNotExists(string path);
};
#endif //FILESYSTEM_H
|
PancakeSoftware/openHabAI | catflow/cpp/include/util/util.h | <reponame>PancakeSoftware/openHabAI<gh_stars>1-10
/*
* File: util.h
* Author: <NAME>
*
*/
#ifndef OPENHABAI_UTIL_H
#define OPENHABAI_UTIL_H
#include <string>
#include <vector>
#include <algorithm>
#include <JsonObject.h>
using namespace std;
inline vector<string> intersect(vector<string> &v1, vector<string> &v2) {
vector<string> v3;
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v3));
return v3;
}
/**
* contians vector1 minimal one element of vector2
* @param vector1
* @param vector2
* @return
*/
inline bool contains(vector<string> &vector1, vector<string> vector2) {
return intersect(vector1, vector2).size() >= 1;
}
class Range: public JsonObject{
public:
float from = 0;
float to = 0;
int steps = 1;
void params() override {
param("from", from);
param("to", to);
param("steps", steps);
}
};
class RangeParam: public Range{
public:
int id;
void params() override { Range::params();
param("id", id);
}
};
class ValueParam: public JsonObject{
public:
int id;
float value;
float tolerance;
void params() override {
param("id", id);
param("value", value);
param("tolerance", tolerance);
}
};
/**
* interpolate n-dimensional data-grid by given ranges for each dimension
* @param inputRanges ranges for each dimension (from, to, steps)
* @param inputData to this vector the data for each dimension is appended, via this param you can set initial dimension data
* @return list of points(has in each dimension a value) in the grid
*/
inline vector<vector<float>> &_createInputDataGrid(vector<RangeParam>::const_iterator input, vector<RangeParam>::const_iterator inputEnd,
vector<vector<float>> &inputDataList, vector<float> inputPoint)
{
if (input == inputEnd)
{
//debug("create dataPoint at "+ Json{inputData}.dump());
if (!inputPoint.empty())
inputDataList.push_back(inputPoint); // add new point
return inputDataList;
}
// calc increase step for rangeInput
float step;
if (input->steps > 0)
step = ((input->to - input->from) / input->steps);
else
step = 0;
step = (step > 0) ? step : 0;
//debug("progress input (perStep+="+to_string(step)+")"+ input->toJson().dump());
// for each point of range
for (float i = input->from; i <= input->to; i += step)
{
vector<float> nInputPoint = inputPoint;
nInputPoint[input->id] = i;
_createInputDataGrid(input+1, inputEnd, inputDataList, nInputPoint);
if (step == 0)
break;
}
};
/**
* interpolate n-dimensional data-grid by given ranges for each dimension
* @param inputRanges ranges for each dimension (from, to, steps)
* @return list of points(has in each dimension a value) in the grid
*/
inline vector<vector<float>> createInputDataGrid(const vector<RangeParam> &inputRanges) {
vector<vector<float>> inputDataList{};
_createInputDataGrid(inputRanges.begin(), inputRanges.end(), inputDataList, vector<float>(inputRanges.size()));
return inputDataList;
}
/**
* interpolate n-dimensional(=inputRanges.size + fixedInputs.size) data-grid by given ranges for each dimension
* @param inputRanges ranges for each dimension (from, to, steps)
* @param fixedInputs appended to each point
* @return list of points(has in each dimension a value) in the grid
*/
inline vector<vector<float>> createInputDataGrid(const vector<RangeParam> &inputRanges, vector<ValueParam> fixedInputs) {
vector<vector<float>> inputDataList{};
vector<float> pointInitInputs(inputRanges.size()+fixedInputs.size());
// fill fixed inputs
for (auto fixed : fixedInputs)
pointInitInputs[fixed.id] = fixed.value;
_createInputDataGrid(inputRanges.begin(), inputRanges.end(),
inputDataList, pointInitInputs);
return inputDataList;
}
/**
* make 2d vector to flat 1d vector
* @tparam T
* @param orig
* @return
*/
template<typename T>
inline std::vector<T> flatten2DVec(const std::vector<std::vector<T>> &orig)
{
std::vector<T> ret;
for(const auto &v: orig)
ret.insert(ret.end(), v.begin(), v.end());
return ret;
}
#endif //OPENHABAI_UTIL_H
|
xuanfengleiting/weChat | weChat/weChat/Classes/Model/Person.h | <filename>weChat/weChat/Classes/Model/Person.h
//
// Person.h
// weChat
//
// Created by jnl on 2018/1/8.
// Copyright © 2018年 newenergy. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
@end
|
eilerstim/system-monitor | include/processor.h | <reponame>eilerstim/system-monitor
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include<vector>
#include<string>
class Processor {
public:
Processor() : prevTotal(0.0), prevIdle(0.0) {};
float Utilization();
std::vector<long> toLong(std::vector<std::string> values);
private:
long prevTotal;
long prevIdle;
};
#endif |
eilerstim/system-monitor | include/process.h | #ifndef PROCESS_H
#define PROCESS_H
#include <string>
#include "linux_parser.h"
/*
Basic class for Process representation
It contains relevant attributes as shown below
*/
class Process {
public:
Process (int pid);
int Pid();
std::string User();
std::string Command();
float CpuUtilization();
std::string Ram();
long int UpTime();
float getCpuUsage() const { return _cpuUsage;};
private:
int _pid;
float _cpuUsage;
enum States {
kUtime = 0,
kStime,
kCutime,
kCstime,
kStarttime
};
};
#endif |
p0lyh3dron/chik | src/modules/engine/stat.c | <filename>src/modules/engine/stat.c
/*
* stat.c -- source file for engine statistics
*
* Authored by Karl "p0lyh3dron" Kreuze on April 16, 2022.
*
* This file is part of the Chik engine.
*
* This file defines the routines for collecting and displaying
* engine statistics.
*/
#include "stat.h"
#include <sys/time.h>
stat_t gStat = { 0 };
/*
* Starts a new frame.
*/
void stat_start_frame() {
struct timeval tv;
gettimeofday( &tv, NULL );
/*
* Get the microseconds since the epoch.
*
* The interesting array index increments the
* frame count, and bounds it to not exceed
* the maximum number of averaging frames.
*/
gStat.aFrameTimes[ gStat.aFrames++ % FRAMES_AVG_COUNT ] = tv.tv_sec * 1000000 + tv.tv_usec;
/*
* Calculate the fps.
*/
gStat.aFrameRate = 0;
for ( u64 i = 0; i <= FRAMES_AVG_COUNT; i++ ) {
/*
* Divide out the microsecond precision, and subtract from previous time.
* The use of the modulo operator is to prevent the frame rate from
* going negative.
*/
gStat.aFrameRate += (
gStat.aFrameTimes[ ( gStat.aFrames + i + 1 ) % FRAMES_AVG_COUNT ]
- gStat.aFrameTimes[ ( gStat.aFrames + i ) % FRAMES_AVG_COUNT ]
) / 100000.0f;
}
gStat.aFrameRate /= ( FRAMES_AVG_COUNT - 1 );
gStat.aFrameRate = 1.0f / gStat.aFrameRate;
}
/*
* Returns the engine statistics.
*
* @return stat_t * The engine statistics.
*/
stat_t *stat_get() {
return &gStat;
}
/*
* Returns the frame rate.
*
* @return f32 The frame rate.
*/
f32 stat_get_frame_rate() {
return gStat.aFrameRate;
}
/*
* Returns the number of frames.
*
* @return s64 The number of frames.
*/
s64 stat_get_frames() {
return gStat.aFrames;
}
/*
* Returns the start time.
*
* @return s64 The start time.
*/
s64 stat_get_start_time() {
return gStat.aStartTime;
} |
p0lyh3dron/chik | src/modules/gfx/abstract.h | /*
* abstract.h -- header file for declaring abstract functions
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Included here are the abstract functions used by the Chik engine.
* These functions are used to abstract the underlying graphics
* library used by the engine.
*/
#pragma once
#include "libchik.h"
/*
* Initialize libraries used for drawing.
*/
void platform_init( void );
/*
* Renders buffer to the screen.
*/
void platform_draw_frame( void ); |
p0lyh3dron/chik | src/modules/engine/engine.h | <filename>src/modules/engine/engine.h<gh_stars>1-10
/*
* engine.h -- header for engine module
*
* Authored by Karl "p0lyh3dron" Kreuze on April 16, 2022.
*
* This file is part of the Chik engine.
*
* The brain of Chik Engine resides in this module. At
* her current state, this module will handle the loading
* of all the other modules, and the act as an interface
* between the modules that the game code will use.
*/
#pragma once
#define ENGINE_MAX_MODULES 16
#include "libchik.h"
typedef struct {
dl_handle_t aHandle;
const s8 *apName;
} module_t;
/*
* Initializes the engine with the specified modules.
*
* @param const s8 * The name of the modules to initialize.
* @param ... The other modules to initialize.
*
* @return u32 Returns 0 on failure, 1 on success.
*/
u32 engine_init( const s8 *spModules, ... );
/*
* Loads a function from the engine for external use.
*
* @param const s8 * The name of the function to load.
*
* @return void * Returns a pointer to the function.
*/
void *engine_load_function( const s8 *spName );
/*
* Frees the engine.
*/
void engine_free(); |
p0lyh3dron/chik | src/modules/engine/stat.h | /*
* stat.h -- header file for engine statistics
*
* Authored by Karl "p0lyh3dron" Kreuze on April 16, 2022.
*
* This file is part of the Chik engine.
*
* The following declares the types and functions used
* for taking engine statistics, such as the number of
* frames rendered, the start time, etc.
*/
#pragma once
#define FRAMES_AVG_COUNT 10
#include "libchik.h"
typedef struct {
s64 aFrames;
s64 aFrameTimes[ FRAMES_AVG_COUNT ];
f32 aFrameRate;
s64 aStartTime;
} stat_t;
/*
* Starts a new frame.
*/
void stat_start_frame();
/*
* Returns the engine statistics.
*
* @return stat_t * The engine statistics.
*/
stat_t *stat_get();
/*
* Returns the frame rate.
*
* @return f32 The frame rate.
*/
f32 stat_get_frame_rate();
/*
* Returns the number of frames.
*
* @return s64 The number of frames.
*/
s64 stat_get_frames();
/*
* Returns the start time.
*
* @return s64 The start time.
*/
s64 stat_get_start_time(); |
p0lyh3dron/chik | src/modules/engine/engine.c | /*
* engine.c -- source for engine module
*
* Authored by Karl "p0lyh3dron" Kreuze on April 16, 2022.
*
* This file is part of the Chik engine.
*
* The brain of Chik Engine resides in this module. This
* file will define how the engine will do module handling.
*/
#include "engine.h"
#include <time.h>
#include <stdarg.h>
#include "stat.h"
mempool_t *gpEnginePool = nullptr;
module_t gpModules[ ENGINE_MAX_MODULES ] = { 0 };
/*
* Initializes the engine with the specified modules.
*
* @param const s8 * The name of the modules to initialize.
* @param ... The other modules to initialize.
*
* @return u32 Returns 0 on failure, 1 on success.
*/
u32 engine_init( const s8 *modules, ... ) {
/*
* Set the start time.
*/
stat_t *pStat = stat_get();
pStat->aStartTime = time( nullptr );
/*
* Initialize the engine modules.
*/
va_list args;
u32 result = 1;
u32 moduleIndex = 0;
va_start( args, modules );
while ( modules ) {
dl_handle_t h = dl_open( modules );
if ( h == nullptr ) {
log_fatal( "u32 engine_init( const s8 *, ... ): Unable to open module: %s\n", modules );
result = 0;
break;
}
u32 ( *entry )( void * ) = dl_sym( h, "chik_module_entry" );
if ( entry == nullptr || !entry( &engine_load_function ) ) {
log_warn( "u32 engine_init( const s8 *, ... ): Unable to load module entry: %s\n", modules );
}
gpModules[ moduleIndex++ ] = ( module_t ){ h, modules };
modules = va_arg( args, const s8 * );
}
va_end( args );
return result;
}
/*
* Loads a function from the engine for external use.
*
* @param const s8 * The name of the function to load.
*
* @return void * Returns a pointer to the function.
*/
void *engine_load_function( const s8 *spName ) {
void *pFunc = nullptr;
for ( u64 i = 0; i < ENGINE_MAX_MODULES; i++ ) {
/*
* If the module isn't null, we'll try to load the function.
*/
if ( gpModules[ i ].apName && gpModules[ i ].aHandle ) {
pFunc = dl_sym( gpModules[ i ].aHandle, spName );
if ( pFunc ) {
break;
}
}
}
return pFunc;
}
/*
* Frees the engine.
*/
__attribute__( ( destructor ) )
void engine_free() {
for ( u64 i = 0; i < ENGINE_MAX_MODULES; ++i ) {
if ( gpModules[ i ].aHandle ) {
dl_close( gpModules[ i ].aHandle );
}
}
} |
p0lyh3dron/chik | src/modules/gfx/camera.h | /*
* camera.h -- header for camera functions
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Included in the Chik engine is the camera, which is used to
* render the scene.
*/
#pragma once
#include "libchik.h"
typedef struct {
vec3_t aPosition;
vec2_t aDirection;
float aFOV;
float aNear;
float aFar;
float aAspect;
} camera_t;
extern camera_t *gpCamera;
/*
* Creates a view matrix for the camera.
*
* @param camera_t * The camera.
*
* @return mat4_t The view matrix.
*/
mat4_t camera_view( camera_t *spCamera );
/*
* Creates a projection matrix for the camera.
*
* @param camera_t * The camera.
*
* @return mat4_t The projection matrix.
*/
mat4_t camera_projection( camera_t *spCamera ); |
p0lyh3dron/chik | src/modules/gfx/abstract.c | <reponame>p0lyh3dron/chik<filename>src/modules/gfx/abstract.c
/*
* abstract.c -- header file for declaring abstract functions
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Included here are the definitions for the abstract functions used by the Chik engine.
*/
#include "abstract.h"
#include "libchik.h"
#include "surface.h"
#include "rendertarget.h"
chik_surface_t *gpSurface = NULL;
rendertarget_t *gpRenderTarget = NULL;
/*
* Initialize libraries used for drawing.
*/
__attribute__( ( constructor ) )
void platform_init( void ) {
s32 width = args_get_int( "-w" );
s32 height = args_get_int( "-h" );
if ( width == -1 || height == -1 ) {
width = DEFAULT_WIDTH;
height = DEFAULT_HEIGHT;
}
#if USE_SDL
gpSurface = surface_create( width, height, 32 );
if( gpSurface == NULL ) {
log_fatal( "Could not create surface." );
}
s8 *pTitle = app_get_name();
if ( pTitle == NULL ) {
pTitle = WINDOW_TITLE;
}
SDL_Window *pWindow = SDL_CreateWindow( pTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, gpSurface->aWidth, gpSurface->aHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
if( pWindow == NULL ) {
log_fatal( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
}
SDL_Renderer *pRenderer = SDL_CreateRenderer( pWindow, -1, SDL_RENDERER_ACCELERATED );
if( pRenderer == NULL ) {
log_fatal( "Renderer could not be created! SDL_Error: %s\n", SDL_GetError() );
}
SDL_Texture *pTexture = SDL_CreateTexture( pRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, gpSurface->aWidth, gpSurface->aHeight );
if( pTexture == NULL ) {
log_fatal( "Texture could not be created! SDL_Error: %s\n", SDL_GetError() );
}
gpSurface->apWindow = pWindow;
gpSurface->apRenderer = pRenderer;
gpSurface->apTexture = pTexture;
#endif /* USE_SDL */
}
#if USE_SDL
/*
* Returns the SDL window.
*
* @return SDL_Window * The SDL window.
*/
SDL_Window *get_window( void ) {
return gpSurface->apWindow;
}
#endif /* USE_SDL */
/*
* Renders buffer to the screen.
*/
void platform_draw_frame( void ) {
gpRenderTarget = rendertarget_get_backbuffer();
#if USE_SDL
SDL_RenderClear( gpSurface->apRenderer );
SDL_UpdateTexture( gpSurface->apTexture, NULL, gpRenderTarget->apTarget->apData, gpSurface->aWidth * sizeof( u32 ) );
SDL_RenderCopy( gpSurface->apRenderer, gpSurface->apTexture, NULL, NULL );
SDL_RenderPresent( gpSurface->apRenderer );
#endif /* USE_SDL */
image_clear( gpRenderTarget->apTarget, 0xFF000000 );
} |
p0lyh3dron/chik | src/modules/gfx/surface.c | /*
* surface.c -- header file to interface with the draw surface
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Included here are the functions used to interface with the
* draw surface.
*/
#include "surface.h"
static chik_surface_t *gpSurface = NULL;
/*
* Create a new surface.
*
* @param u32 The width of the surface.
* @param u32 The height of the surface.
* @param u32 The number of bits per pixel.
*
* @return chik_surface_t * The new surface.
* NULL on failure.
*/
chik_surface_t *surface_create( u32 sWidth, u32 sHeight, u32 sBpp ) {
chik_surface_t *pSurface = NULL;
pSurface = ( chik_surface_t * )malloc( sizeof( chik_surface_t ) );
if( pSurface == NULL ) {
log_fatal( "Could not allocate memory for surface." );
return NULL;
}
pSurface->aWidth = sWidth;
pSurface->aHeight = sHeight;
pSurface->aBPP = sBpp;
gpSurface = pSurface;
return pSurface;
}
/*
* Gets the surface.
*
* @return chik_surface_t * The surface.
* NULL on failure.
*/
chik_surface_t *surface_get( void ) {
return gpSurface;
}
/*
* Destroy a surface.
*
* @param chik_surface_t * The surface to destroy.
*/
void surface_destroy( chik_surface_t *spSurface ) {
free( spSurface );
} |
p0lyh3dron/chik | src/modules/gfx/vertexasm.c | /*
* vertexasm.c -- source for the vertex assembler
*
* Authored by Karl "p0lyh3dron" Kreuze on June 12, 2022.
*
* This file is part of the Chik engine.
*
* The definitions for the vertex assembler are in here.
*/
#include "vertexasm.h"
#include "cull.h"
v_layout_t gLayout = { .aAttribs = { 0 }, .aCount = 0 };
void *gpUniform = nullptr;
/*
* Sets the vertex assembler's vertex layout.
*
* @param v_layout_t The layout of the vertex data.
*/
void vertexasm_set_layout( v_layout_t sLayout ) {
gLayout = sLayout;
cull_set_vertex_size( gLayout.aStride );
}
/*
* Extracts the position from a vertex.
*
* @param void * The raw vertex data.
*
* @return vec4_t The position of the vertex.
*/
vec4_t vertex_get_position( void *spV ) {
s64 i;
for ( i = 0; i < gLayout.aCount; i++ ) {
if ( gLayout.aAttribs[ i ].aUsage == V_POS ) {
break;
}
}
if ( i == gLayout.aCount ) {
return ( vec4_t ){ 0, 0, 0, 0 };
}
return *( vec4_t * )( ( u8 * )spV + gLayout.aAttribs[ i ].aOffset );
}
/*
* Sets the position of a vertex.
*
* @param void * The raw vertex data.
* @param vec4_t The position of the vertex.
*/
void vertex_set_position( void *spV, vec4_t sPosition ) {
s64 i;
for ( i = 0; i < gLayout.aCount; i++ ) {
if ( gLayout.aAttribs[ i ].aUsage == V_POS ) {
break;
}
}
if ( i == gLayout.aCount ) {
return;
}
*( vec4_t * )( ( u8 * )spV + gLayout.aAttribs[ i ].aOffset ) = sPosition;
}
/*
* Builds a new vertex given two vertices and a normalized difference.
*
* @param void * The raw vertex data of the first vertex.
* @param void * The raw vertex data of the second vertex.
* @param f32 The normalized difference between the two vertices.
*
* @return void * The raw vertex data of the new vertex.
*/
void *vertex_build_interpolated( void *spV1, void *spV2, f32 sDiff ) {
static u8 buf[ VERTEX_ASM_MAX_VERTEX_SIZE ];
s64 i;
for ( i = 0; i < gLayout.aCount; i++ ) {
vec_interp(
buf + gLayout.aAttribs[ i ].aOffset,
spV1 + gLayout.aAttribs[ i ].aOffset,
spV2 + gLayout.aAttribs[ i ].aOffset,
sDiff,
gLayout.aAttribs[ i ].aFormat
);
}
return buf;
}
/*
* Scales a vertex by a scalar.
*
* @param void * The raw vertex data.
* @param f32 The scalar to scale the vertex by.
* @param u32 A usage flag that determines how to scale the vertex.
*
* @return void * The raw vertex data of the scaled vertex.
*/
void *vertex_scale( void *spV, f32 sScale, u32 sFlags ) {
static u8 buf[ VERTEX_ASM_MAX_VERTEX_SIZE ];
s64 i;
for ( i = 0; i < gLayout.aCount; i++ ) {
if ( !( gLayout.aAttribs[ i ].aUsage & sFlags ) ) {
vec_scale(
buf + gLayout.aAttribs[ i ].aOffset,
spV + gLayout.aAttribs[ i ].aOffset,
sScale,
gLayout.aAttribs[ i ].aFormat
);
}
else {
memcpy( buf + gLayout.aAttribs[ i ].aOffset, spV + gLayout.aAttribs[ i ].aOffset, gLayout.aAttribs[ i ].aStride );
}
}
return buf;
}
/*
* Binds the fragment shader's uniform data to the vertex assembler.
*
* @param void * The raw uniform data.
*/
void vertexasm_bind_uniform( void *spUniform ) {
gpUniform = spUniform;
}
/*
* Applies the fragments of a fragment shader to a pixel.
*
* @param void * The raw fragment data.
* @param fragment_t * The pixel to apply the fragment to.
*/
void fragment_apply( void *spF, fragment_t *spP ) {
gLayout.apFunc( spP, spF, gpUniform );
} |
p0lyh3dron/chik | src/modules/gfx/surface.h | <reponame>p0lyh3dron/chik
/*
* surface.h -- header file to interface with the draw surface
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Included here are the functions used to interface with the
* draw surface.
*/
#pragma once
#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480
#define WINDOW_TITLE "Chik ( Version 1.0 )"
#if USE_SDL
#include <SDL2/SDL.h>
#endif /* USE_SDL */
#include "libchik.h"
typedef struct {
u32 aWidth;
u32 aHeight;
u32 aBPP;
#if USE_SDL
SDL_Window *apWindow;
SDL_Renderer *apRenderer;
SDL_Texture *apTexture;
#endif /* USE_SDL */
} chik_surface_t;
/*
* Create a new surface.
*
* @param u32 The width of the surface.
* @param u32 The height of the surface.
* @param u32 The number of bits per pixel.
*
* @return chik_surface_t * The new surface.
* NULL on failure.
*/
chik_surface_t *surface_create( u32 sWidth, u32 sHeight, u32 sBpp );
/*
* Gets the surface.
*
* @return chik_surface_t * The surface.
* NULL on failure.
*/
chik_surface_t *surface_get( void );
/*
* Destroy a surface.
*
* @param chik_surface_t * The surface to destroy.
*/
void surface_destroy( chik_surface_t *spSurface ); |
p0lyh3dron/chik | src/modules/gfx/vertexasm.h | /*
* vertexasm.h -- header for the vertex assembler
*
* Authored by Karl "p0lyh3dron" Kreuze on June 12, 2022.
*
* This file is part of the Chik engine.
*
* The declarations in this file are for the vertex assembler.
* The vertex assembler is used to manage raw vertex data, such as
* position for rasterization. It will also create new vertex data for
* interpolation during rasterization.
*/
#ifndef CHIK_GFX_VERTEXASM_H
#define CHIK_GFX_VERTEXASM_H
#include "libchik.h"
#define VERTEX_ASM_MAX_VERTEX_SIZE ( 1024 )
/*
* Sets the vertex assembler's vertex layout.
*
* @param v_layout_t The layout of the vertex data.
*/
void vertexasm_set_layout( v_layout_t sLayout );
/*
* Extracts the position from a vertex.
*
* @param void * The raw vertex data.
*
* @return vec4_t The position of the vertex.
*/
vec4_t vertex_get_position( void *spV );
/*
* Sets the position of a vertex.
*
* @param void * The raw vertex data.
* @param vec4_t The position of the vertex.
*/
void vertex_set_position( void *spV, vec4_t sPosition );
/*
* Builds a new vertex given two vertices and a normalized difference.
*
* @param void * The raw vertex data of the first vertex.
* @param void * The raw vertex data of the second vertex.
* @param f32 The normalized difference between the two vertices.
*
* @return void * The raw vertex data of the new vertex.
*/
void *vertex_build_interpolated( void *spV1, void *spV2, f32 sDiff );
/*
* Scales a vertex by a scalar.
*
* @param void * The raw vertex data.
* @param f32 The scalar to scale the vertex by.
* @param u32 A usage flag that determines how to scale the vertex.
*
* @return void * The raw vertex data of the scaled vertex.
*/
void *vertex_scale( void *spV, f32 sScale, u32 sFlags );
/*
* Binds the fragment shader's uniform data to the vertex assembler.
*
* @param void * The raw uniform data.
*/
void vertexasm_bind_uniform( void *spUniform );
/*
* Applies the fragments of a fragment shader to a pixel.
*
* @param void * The raw fragment data.
* @param fragment_t * The pixel to apply the fragment to.
*/
void fragment_apply( void *spF, fragment_t *spP );
#endif /* CHIK_GFX_VERTEXASM_H */ |
p0lyh3dron/chik | src/modules/gfx/cull.h | /*
* cull.h -- header for culling/clipping routines
*
* Authored by Karl "p0lyh3dron" Kreuze on June 12, 2022.
*
* This file is part of the Chik engine.
*
* As of now, the culling routines consist of just frustum culling,
* which tests a line segment against a plane, and interpolates a new
* point on the line segment if it intersects the plane.
*/
#ifndef CHIK_GFX_CULL_H
#define CHIK_GFX_CULL_H
#include "libchik.h"
/*
* Sets the current vertex size.
*
* @param u32 The size of the vertex data.
*/
void cull_set_vertex_size( u32 sSize );
/*
* Clips a pair of vertices.
*
* @param plane_t * The plane to clip against.
* @param void * The first vertex.
* @param void * The second vertex.
* @param void * The clipped vertex.
* @param u32 True if this is the first vertex.
*
* @return u32 Bitmask of the clip flags.
* 0x0 = keep the first vertex.
* 0x1 = modify first vertex with the clipped.
*
*/
u32 cull_clip_vertex( plane_t *spP, void *spV0, void *spV1, void *spRet, u32 sFirst );
/*
* Inserts a vertex into a clipped vertex list.
*
* @param void * The vertex to insert.
* @param void ** The list of vertices.
* @param u32 The target index.
* @param u32 The number of vertices in the list.
* @param u32 The list size.
*/
void cull_insert_vertex( void *spV, void **spList, u32 sIndex, u32 sCount, u32 sSize );
/*
* Removes a vertex from a clipped vertex list.
*
* @param u32 The index to remove.
* @param void ** The list of vertices.
* @param u32 The number of vertices in the list.
* @param u32 The list size.
*/
void cull_remove_vertex( u32 sIndex, void **spList, u32 sCount, u32 sSize );
/*
* Creates the view frustum.
*/
void cull_create_frustum();
/*
* Clips a triangle.
*
* Reference: https://youtu.be/hxOw_p0kLfI
*
* @param void * The first vertex.
* @param void * The second vertex.
* @param void * The third vertex.
* @param s32 * The number of new vertices.
*
* @return chik_vertex_t * The new vertices.
*/
chik_vertex_t *cull_clip_triangle( void *spV0, void *spV1, void *spV2, s32 *spNumVertices );
#endif /* CHIK_GFX_CULL_H */ |
p0lyh3dron/chik | src/modules/gfx/drawable.h | <gh_stars>1-10
/*
* drawable.h -- header for general drawable functionality
*
* Authored by Karl "p0lyh3dron" Kreuze on June 7, 2022.
*
* This file is part of the Chik engine.
*
* The drawables refer to objects such as vertex buffers, textures,
* shaders, and so on. In it's primitive state, we'll allow for loading
* vertex buffers, and drawing a texture on to them.
*/
#pragma once
#include "libchik.h"
#include "image.h"
typedef struct {
void *apData;
u32 aVStride;
u32 aSize;
v_layout_t aLayout;
} vbuffer_t;
typedef struct {
handle_t aVBuf;
/*
* Will be replaced with material_t *
*/
handle_t aTex;
} mesh_t;
/*
* Initializes resources for below functions.
*
* @return u32 Whether or not the initialization was successful.
* 1 = success, 0 = failure.
*/
u32 init_drawable_resources();
/*
* Creates a vertex buffer.
*
* @param void * The vertex data.
* @param u32 The size of the vertex data.
* @param u32 The stride of the vertex data.
* @param v_layout_t The layout of the vertex data.
*
* @return handle_t The vertex buffer.
* INVALID_HANDLE if the vertex buffer could not be created.
* The mesh should be freed with vbuffer_free().
*/
handle_t vbuffer_create( void *spVerts, u32 sSize, u32 sVStride, v_layout_t sLayout );
/*
* Frees a vertex buffer.
*
* @param handle_t The vertex buffer to free.
*/
void vbuffer_free( handle_t sVBuffer );
/*
* Creates a texture from a file.
*
* @param s8 * The path to the texture file.
* @param u32 The format of the texture.
*
* @return handle_t The texture.
*/
handle_t texture_create_from_file( s8 *spPath, u32 sFormat );
/*
* Frees a texture.
*
* @param handle_t The texture to free.
*/
void texture_free( handle_t sTex );
/*
* Creates a mesh.
*
* @param handle_t The vertex buffer.
* @param handle_t The texture.
*
* @return handle_t The mesh.
*/
handle_t mesh_create( handle_t sVBuffer, handle_t sTex );
/*
* Sets the vertex buffer of a mesh.
*
* @param handle_t The mesh.
* @param handle_t The vertex buffer.
*/
void mesh_set_vertex_buffer( handle_t sMesh, handle_t sVBuffer );
/*
* Sets the texture of a mesh.
*
* @param handle_t The mesh.
* @param handle_t The texture.
*/
void mesh_set_texture( handle_t sMesh, handle_t sTex );
/*
* Translates a mesh.
*
* @param vec3_t The translation vector.
*/
void mesh_translate( vec3_t sTranslation );
/*
* Rotates a mesh.
*
* @param vec3_t The rotation vector.
*/
void mesh_rotate( vec3_t sRotation );
/*
* Draws a vertex buffer.
*
* @param handle_t The handle to the vertex buffer.
*/
void vbuffer_draw( handle_t sBuffer );
/*
* Draws a mesh.
*
* @param handle_t The mesh.
*/
void mesh_draw( handle_t sMesh );
/*
* Frees a mesh.
*
* @param handle_t The mesh to free.
*/
void mesh_free( handle_t sMesh ); |
p0lyh3dron/chik | src/modules/gfx/rendertarget.c | <filename>src/modules/gfx/rendertarget.c
/*
* rendertarget.c -- source for using render targets
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Here are the functions used for creating and using render targets.
*/
#include "rendertarget.h"
#include "surface.h"
rendertarget_t **gpRenderTargets = NULL;
rendertarget_t *gpBackBuffer = NULL;
/*
* Creates a render target.
*
* @param u32 The width of the render target.
* @param u32 The height of the render target.
* @param u32 The format of the render target.
*
* @return rendertarget_t * The render target.
* NULL if the render target could not be created.
* The render target should be freed with rendertarget_free().
*/
rendertarget_t *rendertarget_create( u32 sWidth, u32 sHeight, u32 sFormat ) {
rendertarget_t *pRenderTarget = malloc( sizeof( rendertarget_t ) );
if( pRenderTarget == NULL ) {
log_error( "Could not allocate memory for render target." );
}
image_t *pImage = image_create( sWidth, sHeight, sFormat );
if( pImage == NULL ) {
log_error( "Could not allocate memory for render target image." );
}
pRenderTarget->apTarget = pImage;
/*
* Make a new list of render targets if there is none.
*/
if ( gpRenderTargets == NULL ) {
gpRenderTargets = malloc( sizeof( rendertarget_t * ) * 2 );
if( gpRenderTargets == NULL ) {
log_error( "Could not allocate memory for render target list." );
}
gpRenderTargets[ 0 ] = pRenderTarget;
gpRenderTargets[ 1 ] = NULL;
}
else {
u32 i = 0;
while ( gpRenderTargets[ i ] != NULL ) {
i++;
}
gpRenderTargets[ i ] = pRenderTarget;
gpRenderTargets = realloc( gpRenderTargets, sizeof( rendertarget_t * ) * ( i + 1 ) );
if( gpRenderTargets == NULL ) {
log_error( "Could not reallocate memory for render target list." );
}
}
return pRenderTarget;
}
/*
* Frees a render target.
*
* @param rendertarget_t * The render target to free.
*/
void rendertarget_free( rendertarget_t *spRenderTarget ) {
if( spRenderTarget == NULL ) {
log_error( "Render target is NULL.\n" );
return;
}
image_free( spRenderTarget->apTarget );
free( spRenderTarget );
}
/*
* Gets a list of render targets.
*
* @return rendertarget_t * The list of render targets.
* NULL if the list could not be created.
*/
rendertarget_t **rendertarget_get_list( void ) {
return gpRenderTargets;
}
/*
* Create backbuffer render target.
*
* @return rendertarget_t * The render target.
* NULL if the render target could not be created.
* The render target should be freed with rendertarget_free().
*/
__attribute__( ( constructor ) )
rendertarget_t *rendertarget_create_backbuffer( void ) {
chik_surface_t *pSurface = surface_get();
rendertarget_t *pRenderTarget = rendertarget_create( pSurface->aWidth, pSurface->aHeight, 69 );
if( pRenderTarget == NULL ) {
log_error( "Could not create backbuffer render target." );
return NULL;
}
gpBackBuffer = pRenderTarget;
return pRenderTarget;
}
/*
* Gets the backbuffer render target.
*
* @return rendertarget_t * The render target.
* NULL if the render target could not be created.
* The render target should be freed with rendertarget_free().
*/
rendertarget_t *rendertarget_get_backbuffer( void ) {
return gpBackBuffer;
}
/*
* Frees all render targets.
*/
__attribute__( ( destructor ) )
void rendertarget_free_all( void ) {
if ( gpRenderTargets == NULL ) {
return;
}
u32 i = 0;
while ( gpRenderTargets[ i ] != NULL ) {
rendertarget_free( gpRenderTargets[ i ] );
i++;
}
free( gpRenderTargets );
gpRenderTargets = NULL;
} |
p0lyh3dron/chik | src/modules/gfx/image.c | /*
* image.c -- source for image functionality
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* This file declares the functions used for loading and manipulating images.
*/
#include "image.h"
#include <malloc.h>
#include <string.h>
/*
* Creates an image.
*
* @param u32 The width of the image.
* @param u32 The height of the image.
* @param u32 The format of the image.
*
* @return image_t * The image.
* NULL if the image could not be created.
* The image should be freed with image_free().
*/
image_t *image_create( u32 sWidth, u32 sHeight, u32 sFormat ) {
image_t *pImage = malloc( sizeof( image_t ) );
if( pImage == NULL ) {
log_error( "Could not allocate memory for image." );
}
pImage->aWidth = sWidth;
pImage->aHeight = sHeight;
pImage->aFormat = sFormat;
/*
* In the future, image data may not be just width * height * format.
* For now, we just allocate the amount of memory we need.
*/
pImage->apData = malloc( sWidth * sHeight * sizeof( u32 ) );
if( pImage->apData == NULL ) {
log_error( "Could not allocate memory for image buffer." );
}
return pImage;
}
/*
* Deduces a file format from a file.
*
* @param const s8 * The file to deduce the format from.
*
* @return file_type_e The file format.
* FILE_TYPE_UNKNOWN if the file could not be deduced.
*/
file_type_e file_type( const s8 *spFile ) {
/*
* We'll be lazy and just check the file extension.
* In the future, we'll need to check the file header.
*/
if( strstr( spFile, ".bmp" ) != NULL ) {
return FILE_TYPE_BMP;
} else if( strstr( spFile, ".png" ) != NULL ) {
return FILE_TYPE_PNG;
} else if( strstr( spFile, ".jpg" ) != NULL ) {
return FILE_TYPE_JPG;
} else {
return FILE_TYPE_UNKNOWN;
}
}
/*
* Loads a bmp image from a file.
*
* @param const s8 * The file to load the image from.
*
* @return image_t * The image.
* NULL if the image could not be loaded.
* The image should be freed with image_free().
*/
image_t *image_load_bmp( const s8 *spFile ) {
FILE *pFile = fopen( spFile, "rb" );
if( pFile == NULL ) {
log_error( "Could not open file %s.", spFile );
return NULL;
}
/*
* Read the file contents into a buffer.
*/
fseek( pFile, 0, SEEK_END );
u32 len = ftell( pFile );
fseek( pFile, 0, SEEK_SET );
u8 *pBuffer = malloc( len );
if( pBuffer == NULL ) {
log_error( "Could not allocate memory for file %s.", spFile );
fclose( pFile );
return NULL;
}
fread( pBuffer, 1, len, pFile );
fclose( pFile );
/*
* Read the header.
*/
bmp_header_t header = *( bmp_header_t * )pBuffer;
header.aWidth = *( u32 * )( pBuffer + 0x12 );
header.aHeight = *( u32 * )( pBuffer + 0x16 );
header.aOffset = *( u32 * )( pBuffer + 0x0A );
if ( *( u16* )header.aMagic != 0x4D42 ) {
log_error( "File %s is not a bmp file.", spFile );
free( pBuffer );
return NULL;
}
/*
* Read the image data.
*/
u8 *pData = ( u8 * )( pBuffer + header.aOffset );
/*
* Create the image.
*/
image_t *pImage = image_create( header.aWidth, header.aHeight, 32 );
if( pImage == NULL ) {
log_error( "Could not create image." );
free( pBuffer );
return NULL;
}
/*
* Copy the data into the image without the padding.
*/
u32 padding = 0;
s64 i;
for ( i = 0; i < header.aHeight; i++ ) {
/*
* Don't touch.
*/
memcpy( ( u8 * )pImage->apData + ( header.aWidth * i ) * 3, pData + ( header.aWidth * i ) * 3 + i * padding, header.aWidth * 3 );
/*
* Literal magic.
*/
padding += ( ( header.aWidth * 3 ) + padding ) % 4;
}
/*
* Free the buffer.
*/
free( pBuffer );
return pImage;
}
/*
* Creates an image from a file.
*
* @param s8 * The path to the image file.
* @param u32 The format of the image.
*
* @return image_t * The image.
* NULL if the image could not be created.
* The image should be freed with image_free().
*/
image_t *image_create_from_file( s8 *spPath, u32 sFormat ) {
file_type_e type = file_type( spPath );
if( type == FILE_TYPE_UNKNOWN ) {
log_error( "Could not determine file type of image file." );
return NULL;
}
else if ( type == FILE_TYPE_BMP ) {
return image_load_bmp( spPath );
}
}
/*
* Sets a pixel in an image.
*
* @param image_t * The image.
* @param u32 The x coordinate of the pixel.
* @param u32 The y coordinate of the pixel.
* @param u32 The color of the pixel.
*
* @return u32 1 if the pixel was set, 0 if the pixel could not be set.
*/
u32 image_set_pixel( image_t *image, u32 x, u32 y, u32 color ) {
if( x >= image->aWidth || y >= image->aHeight ) {
return 0;
}
image->apData[ y * image->aWidth + x ] = color;
return 1;
}
/*
* Clears an image.
*
* @param image_t * The image.
* @param u32 The color to clear the image with.
*
* @return u32 1 if the image was cleared, 0 if the image could not be cleared.
*/
u32 image_clear( image_t *spImage, u32 sColor ) {
if ( spImage == NULL ) {
return 0;
}
/*
* Fastest way to clear is to memset the entire buffer.
*/
memset( spImage->apData, sColor, spImage->aWidth * spImage->aHeight * sizeof( u32 ) );
return 1;
}
/*
* Frees an image.
*
* @param image_t * The image to free.
*/
void image_free( image_t *pImage ) {
if ( pImage == NULL ) {
log_error( "Tried to free a NULL image." );
return;
}
free( pImage->apData );
free( pImage );
} |
p0lyh3dron/chik | src/modules/gfx/rendertarget.h | <gh_stars>1-10
/*
* rendertarget.h -- header for declaring render targets
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Included is functionality for creating render targets.
* Render targets are individual surfaces that can be rendered to.
*/
#pragma once
#include "libchik.h"
#include "image.h"
#include "camera.h"
typedef struct {
image_t *apTarget;
} rendertarget_t;
/*
* Creates a render target.
*
* @param u32 The width of the render target.
* @param u32 The height of the render target.
* @param u32 The format of the render target.
*
* @return rendertarget_t * The render target.
* NULL if the render target could not be created.
* The render target should be freed with rendertarget_free().
*/
rendertarget_t *rendertarget_create( u32 sWidth, u32 sHeight, u32 sFormat );
/*
* Frees a render target.
*
* @param rendertarget_t * The render target to free.
*/
void rendertarget_free( rendertarget_t *spRenderTarget );
/*
* Gets a list of render targets.
*
* @return rendertarget_t ** The list of render targets.
* NULL if the list could not be created.
*/
rendertarget_t **rendertarget_get_list( void );
/*
* Create backbuffer render target.
*
* @return rendertarget_t * The render target.
* NULL if the render target could not be created.
* The render target should be freed with rendertarget_free().
*/
rendertarget_t *rendertarget_create_backbuffer( void );
/*
* Gets the backbuffer render target.
*
* @return rendertarget_t * The render target.
* NULL if the render target could not be created.
* The render target should be freed with rendertarget_free().
*/
rendertarget_t *rendertarget_get_backbuffer( void );
/*
* Frees all render targets.
*/
void rendertarget_free_all( void ); |
p0lyh3dron/chik | src/modules/gfx/camera.c | <filename>src/modules/gfx/camera.c
/*
* camera.c -- source for camera functions
*
* Authored by Karl "p0lyh3dron" Kreuze on March 25, 2022
*
* This file is part of the Chik engine.
*
* This file defines the camera functionality.
*/
#include "camera.h"
#include <math.h>
camera_t *gpCamera = NULL;
/*
* Creates a view matrix for the camera.
*
* @param camera_t * The camera.
*
* @return mat4_t The view matrix.
*/
mat4_t camera_view( camera_t *spCamera ) {
mat4_t view = m4_identity();
view = m4_mul_m4( view, camera_projection( spCamera ) );
view = m4_mul_m4( view, m4_rotate( spCamera->aDirection.x, ( vec3_t ){ 1, 0, 0 } ) );
view = m4_mul_m4( view, m4_rotate( spCamera->aDirection.y, ( vec3_t ){ 0, 1, 0 } ) );
view = m4_mul_m4( view, m4_translate( spCamera->aPosition ) );
return view;
}
/*
* Creates a projection matrix for the camera.
*
* @param camera_t * The camera.
*
* @return mat4_t The projection matrix.
*/
mat4_t camera_projection( camera_t *spCamera ) {
float fov = 0.5f / tanf( spCamera->aFOV * 0.5f * 3.14159265358979323846f / 180.0f );
/*
* We'll be using the Vulkan projection matrix.
*
* This matrix uses reverse z, so we'll hardcode the
* farz to 0, and nearz to 1.
*
* Stolen from: https://vincent-p.github.io/posts/vulkan_perspective_matrix/#infinite-perspective
*/
mat4_t projection = {
fov / spCamera->aAspect, 0.f, 0.f, 0.f,
0.f, -fov, 0.f, 0.f,
0.f, 0.f, -1.f, 0.f,
0.f, 0.f, 1.f, 0.f
};
return projection;
} |
p0lyh3dron/chik | src/modules/gfx/image.h | /*
* image.h -- header for declaring images
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik engine.
*
* Included is functionality for creating images to be drawn to.
*/
#pragma once
#include "libchik.h"
typedef enum {
FILE_TYPE_UNKNOWN = 0,
FILE_TYPE_BMP,
FILE_TYPE_PNG,
FILE_TYPE_JPG,
} file_type_e;
typedef struct {
s8 aMagic[ 2 ];
u32 aSize;
u32 aReserved;
u32 aOffset;
u32 aHeaderSize;
u32 aWidth;
u32 aHeight;
u16 aPlanes;
u16 aBitsPerPixel;
u32 aCompression;
u32 aImageSize;
u32 aXPixelsPerMeter;
u32 aYPixelsPerMeter;
u32 aColorsUsed;
u32 aColorsImportant;
u32 aRedMask;
u32 aGreenMask;
u32 aBlueMask;
u32 aAlphaMask;
} bmp_header_t;
/*
* Creates an image.
*
* @param u32 The width of the image.
* @param u32 The height of the image.
* @param u32 The format of the image.
*
* @return image_t * The image.
* NULL if the image could not be created.
* The image should be freed with image_free().
*/
image_t *image_create( u32 sWidth, u32 sHeight, u32 sFormat );
/*
* Deduces a file format from a file.
*
* @param const s8 * The file to deduce the format from.
*
* @return file_type_e The file format.
* FILE_TYPE_UNKNOWN if the file could not be deduced.
*/
file_type_e file_type( const s8 *spFile );
/*
* Loads a bmp image from a file.
*
* @param const s8 * The file to load the image from.
*
* @return image_t * The image.
* NULL if the image could not be loaded.
* The image should be freed with image_free().
*/
image_t *image_load_bmp( const s8 *spFile );
/*
* Creates an image from a file.
*
* @param s8 * The path to the image file.
* @param u32 The format of the image.
*
* @return image_t * The image.
* NULL if the image could not be created.
* The image should be freed with image_free().
*/
image_t *image_create_from_file( s8 *spPath, u32 sFormat );
/*
* Sets a pixel in an image.
*
* @param image_t * The image.
* @param u32 The x coordinate of the pixel.
* @param u32 The y coordinate of the pixel.
* @param u32 The color of the pixel.
*
* @return u32 1 if the pixel was set, 0 if the pixel could not be set.
*/
u32 image_set_pixel( image_t *spImage, u32 sX, u32 sY, u32 sColor );
/*
* Clears an image.
*
* @param image_t * The image.
* @param u32 The color to clear the image with.
*
* @return u32 1 if the image was cleared, 0 if the image could not be cleared.
*/
u32 image_clear( image_t *spImage, u32 sColor );
/*
* Frees an image.
*
* @param image_t * The image to free.
*/
void image_free( image_t *pImage ); |
p0lyh3dron/chik | src/modules/gfx/raster.h | <reponame>p0lyh3dron/chik
/*
* raster.h -- header for graphics rasterization stage
*
* Authored by Karl "p0lyh3dron" Kreuze on June 9, 2022
*
* This file is part of the Chik Engine.
*
* The rasterization stage is responsible for rasterizing the
* geometry into a 2D bitmap. Currently, the rasterization stage
* clips the geometry to the viewing frustum, and then rasterizes
* the geometry into a bitmap by drawing scanlines. The clipping
* algorithm should probably be put into another stage/file,
* but it is currently implemented here.
*/
#ifndef CHIK_GFX_RASTER_H
#define CHIK_GFX_RASTER_H
#include "libchik.h"
#include "rendertarget.h"
/*
* Sets the rasterization stage's bitmap.
*
* @param rendertarget_t * The rendertarget to use for rasterization.
*/
void raster_set_rendertarget( rendertarget_t *spTarget );
/*
* Draw a scanline.
*
* @param s32 The screen x coordinate of the start of the scanline.
* @param s32 The screen x coordinate of the end of the scanline.
* @param s32 The screen y coordinate of the scanline.
* @param void * The first vertex of the scanline.
* @param void * The second vertex of the scanline.
*/
void raster_draw_scanline( s32 sX1, s32 sX2, s32 sY, void *spV1, void *spV2 );
/*
* Rasterizes a single triangle.
*
* @param void * The raw vertex data for the first vertex.
* @param void * The raw vertex data for the second vertex.
* @param void * The raw vertex data for the third vertex.
*/
void raster_rasterize_triangle( void *spV1, void *spV2, void *spV3 );
#endif /* CHIK_GFX_RASTER_H */ |
p0lyh3dron/chik | src/modules/gfx/cull.c | <reponame>p0lyh3dron/chik
/*
* cull.h -- header for culling/clipping routines
*
* Authored by Karl "p0lyh3dron" Kreuze on June 12, 2022.
*
* This file is part of the Chik engine.
*
* This file defines the culling/clipping routines.
*/
#include "cull.h"
#include "camera.h"
#include "vertexasm.h"
frustum_t gFrustum;
u32 gVertexSize = 0;
/*
* Sets the current vertex size.
*
* @param u32 The size of the vertex data.
*/
void cull_set_vertex_size( u32 sSize ) {
gVertexSize = sSize;
}
/*
* Clips a pair of vertices.
*
* @param plane_t * The plane to clip against.
* @param void * The first vertex.
* @param void * The second vertex.
* @param void * The clipped vertex.
* @param u32 True if this is the first vertex.
*
* @return u32 Bitmask of the clip flags.
* 0x0 = keep the first vertex.
* 0x1 = modify first vertex with the clipped.
* 0x2 = modify the first vertex of the array.
*
*/
u32 cull_clip_vertex( plane_t *spP, void *spV0, void *spV1, void *spRet, u32 sFirst ) {
vec4_t p0 = vertex_get_position( spV0 );
vec4_t p1 = vertex_get_position( spV1 );
f32 outside = plane_distance( spP, &p0 );
f32 nextOutside = plane_distance( spP, &p1 );
/*
* Check if the triangle is outside the frustum.
*/
if ( outside > 0.f ^ nextOutside > 0.f ) {
f32 t = outside / ( outside - nextOutside );
/*
* Generate a new vertex.
*/
memcpy( spRet, vertex_build_interpolated( spV0, spV1, t ), gVertexSize );
/*
* If our initial vertex is inside, append the new vertex.
*/
if ( outside >= 0.f ) {
return 0b00000011;
}
/*
* Remove the first vertex.
*/
else if ( sFirst ) {
return 0b00000111;
}
/*
* If our initial vertex is outside, replace the first vertex.
*/
else {
return 0b00000010;
}
}
/*
* If both points are inside, keep the vertices, otherwise
* discard them.
*/
else {
if ( outside >= 0.f ) {
/*
* Keep.
*/
return 0b00000001;
}
/*
* Discard the first vertex.
*/
else if ( sFirst ) {
return 0b00000101;
}
else {
/*
* Discard.
*/
return 0b00000000;
}
}
}
/*
* Inserts a vertex into a clipped vertex list.
*
* @param void * The vertex to insert.
* @param void ** The list of vertices.
* @param u32 The target index.
* @param u32 The number of vertices in the list.
* @param u32 The list size.
*/
void cull_insert_vertex( void *spV, void **spList, u32 sIndex, u32 sCount, u32 sSize ) {
if ( sIndex >= sSize ) {
log_error( "Index out of bounds.\n" );
return;
}
if ( sCount >= sSize ) {
log_error( "List is full.\n" );
return;
}
/*
* Shift the vertices down.
*/
for ( u32 i = sCount; i > sIndex; i-- ) {
memcpy( ( u8 * )spList + i * VERTEX_ASM_MAX_VERTEX_SIZE, ( u8 * )spList + ( i - 1 ) * VERTEX_ASM_MAX_VERTEX_SIZE, gVertexSize );
}
/*
* Insert the vertex.
*/
memcpy( ( u8 * )spList + sIndex * VERTEX_ASM_MAX_VERTEX_SIZE, spV, gVertexSize );
}
/*
* Removes a vertex from a clipped vertex list.
*
* @param u32 The index to remove.
* @param void ** The list of vertices.
* @param u32 The number of vertices in the list.
* @param u32 The list size.
*/
void cull_remove_vertex( u32 sIndex, void **spList, u32 sCount, u32 sSize ) {
if ( sIndex >= sSize ) {
log_error( "Index out of bounds.\n" );
return;
}
if ( sCount <= 0 ) {
log_error( "List is empty.\n" );
return;
}
/*
* Shift the vertices up.
*/
for ( u32 i = sIndex; i < sCount - 1; i++ ) {
/*
* The scope doesn't seem to know that void **spList is a u8[][], so we'll
* use direct memory access. I hope this works on other platforms.
*/
memcpy( ( u8 * )spList + i * VERTEX_ASM_MAX_VERTEX_SIZE, ( u8 * )spList + ( i + 1 ) * VERTEX_ASM_MAX_VERTEX_SIZE, gVertexSize );
}
}
/*
* Creates the view frustum.
*/
void cull_create_frustum() {
f32 n;
f32 f;
if ( !gpCamera ) {
n = 0.1f;
f = 100.f;
}
else {
n = gpCamera->aNear;
f = gpCamera->aFar;
}
vec2_t nsw = { -n, -n };
vec2_t nse = { n, -n };
vec2_t nne = { n, n };
vec2_t nnw = { -n, n };
vec2_t fsw = { -f, -f };
vec2_t fse = { f, -f };
vec2_t fne = { f, f };
vec2_t fnw = { -f, f };
/*
* Plane 0: Near.
* This plane consists of the three points:
* the top-left, bottom-left, and bottom-right.
*/
vec3_t nearTop = { nnw.x, nnw.y, n };
vec3_t nearBot = { nsw.x, nsw.y, n };
vec3_t nearRight = { nne.x, nne.y, n };
plane_from_points( &gFrustum.aPlanes[ 0 ], &nearTop, &nearBot, &nearRight );
/*
* Plane 1: Left.
* This plane consists of the three points ( when directly facing this plane from outside the frustum as if looking through the game camera ):
* the bottom-right, top-right, and top-left.
*/
vec3_t leftCloseBottom = { nsw.x, nsw.y, n };
vec3_t leftCloseTop = { nnw.x, nnw.y, n };
vec3_t leftFarTop = { fnw.x, fnw.y, f };
plane_from_points( &gFrustum.aPlanes[ 1 ], &leftCloseBottom, &leftCloseTop, &leftFarTop );
/*
* Plane 2: Right.
* This plane consists of the three points ( same conditions as above, same for below ):
* the bottom-left, bottom-right, and top-right.
*/
vec3_t rightCloseBottom = { nse.x, nse.y, n };
vec3_t rightFarBottom = { fse.x, fse.y, f };
vec3_t rightFarTop = { fne.x, fne.y, f };
plane_from_points( &gFrustum.aPlanes[ 2 ], &rightCloseBottom, &rightFarBottom, &rightFarTop );
/*
* Plane 3: Top.
* This plane consists of the three points:
* the bottom-left, bottom-right, and top-left.
*/
vec3_t topCloseLeft = { nnw.x, nnw.y, n };
vec3_t topCloseRight = { nne.x, nne.y, n };
vec3_t topFarLeft = { fnw.x, fnw.y, f };
plane_from_points( &gFrustum.aPlanes[ 3 ], &topCloseLeft, &topCloseRight, &topFarLeft );
/*
* Plane 4: Bottom.
* This plane consists of the three points:
* the bottom-right, bottom-left, and top-left.
*/
vec3_t bottomFarRight = { fse.x, fse.y, f };
vec3_t bottomCloseLeft = { nsw.x, nsw.y, n };
vec3_t bottomFarLeft = { fsw.x, fsw.y, f };
plane_from_points( &gFrustum.aPlanes[ 4 ], &bottomFarRight, &bottomCloseLeft, &bottomFarLeft );
/*
* Plane 5: Far.
* This plane consists of the three points:
* the top-left, top-right, bottom-left.
*/
vec3_t farTop = { fnw.x, fnw.y, f };
vec3_t farRight = { fne.x, fne.y, f };
vec3_t farBot = { fsw.x, fsw.y, f };
plane_from_points( &gFrustum.aPlanes[ 5 ], &farTop, &farRight, &farBot );
}
/*
* Clips a triangle.
*
* Reference: https://youtu.be/hxOw_p0kLfI
*
* @param void * The first vertex.
* @param void * The second vertex.
* @param void * The third vertex.
* @param s32 * The number of new vertices.
*
* @return chik_vertex_t * The new vertices.
*/
chik_vertex_t *cull_clip_triangle( void *spV0, void *spV1, void *spV2, s32 *spNumVertices ) {
static u8 vertices[ 8 * VERTEX_ASM_MAX_VERTEX_SIZE ];
u8 v [ VERTEX_ASM_MAX_VERTEX_SIZE ];
u32 numVertices = 3;
u32 removeFirst = 0;
/*
* Copy the vertices into the array.
*/
memcpy( vertices + 0 * VERTEX_ASM_MAX_VERTEX_SIZE, spV0, gVertexSize );
memcpy( vertices + 1 * VERTEX_ASM_MAX_VERTEX_SIZE, spV1, gVertexSize );
memcpy( vertices + 2 * VERTEX_ASM_MAX_VERTEX_SIZE, spV2, gVertexSize );
for ( u64 i = 0; i < ARR_LEN( gFrustum.aPlanes ); ++i ) {
removeFirst = 0;
for ( u64 j = 0; j < numVertices; ) {
u32 ret = cull_clip_vertex(
&gFrustum.aPlanes[ i ],
&vertices[ j * VERTEX_ASM_MAX_VERTEX_SIZE ],
&vertices[ ( ( j + 1 ) % numVertices ) * VERTEX_ASM_MAX_VERTEX_SIZE ],
&v,
j == 0
);
/*
* Remove the first vertex once we are at the end of the loop.
*/
if ( ret & 0b00000100 ) {
removeFirst = 1;
}
/*
* Keep the first vertex.
*/
if ( ret & 0b00000001 ) {
/*
* Insert the new clipped vertex.
*/
if ( ret & 0b00000010 ) {
cull_insert_vertex( &v, &vertices, ++j, numVertices, ARR_LEN( vertices ) );
numVertices++;
}
/*
* No need to insert the new vertex.
*/
++j;
}
else if ( ret & 0b00000010 ) {
/*
* Replace the first vertex.
*/
memcpy( vertices + j * VERTEX_ASM_MAX_VERTEX_SIZE, &v, gVertexSize );
++j;
}
else {
/*
* Erase the first vertex.
*/
cull_remove_vertex( j, &vertices, numVertices--, ARR_LEN( vertices ) );
}
}
/*
* Since we are doing this in place, we need to remove the first vertex occasionally.
*/
if ( removeFirst ) {
cull_remove_vertex( 0, &vertices, numVertices--, ARR_LEN( vertices ) );
}
}
*spNumVertices = numVertices;
return vertices;
} |
p0lyh3dron/chik | src/modules/gfx/raster.c | /*
* raster.c -- source for graphics rasterization stage
*
* Authored by Karl "p0lyh3dron" Kreuze on June 9, 2022
*
* This file is part of the Chik Engine.
*
* The rasterization stage is defined here.
*/
#include "raster.h"
#include "vertexasm.h"
rendertarget_t *gpRasterTarget;
/*
* Sets the rasterization stage's bitmap.
*
* @param rendertarget_t * The rendertarget to use for rasterization.
*/
void raster_set_rendertarget( rendertarget_t *spTarget ) {
gpRasterTarget = spTarget;
}
#ifdef GFX_THREADED
typedef struct {
s32 aX1;
s32 aX2;
s32 aY;
void *apV1;
void *apV2;
} scanline_args_t;
void *raster_scanline_thread( void *apArgs ) {
scanline_args_t *pArgs = ( scanline_args_t * )apArgs;
raster_scanline( pArgs->aX1, pArgs->aX2, pArgs->aY, pArgs->apV1, pArgs->apV2 );
return NULL;
}
#endif /* GFX_THREADED */
/*
* Draw a scanline.
*
* @param s32 The screen x coordinate of the start of the scanline.
* @param s32 The screen x coordinate of the end of the scanline.
* @param s32 The screen y coordinate of the scanline.
* @param void * The first vertex of the scanline.
* @param void * The second vertex of the scanline.
*/
void raster_draw_scanline( s32 sX1, s32 sX2, s32 sY, void *spV1, void *spV2 ) {
/*
* Early out if the scanline is outside the render target,
* or if the line is a degenerate.
*/
if ( sY < 0 || sY >= gpRasterTarget->apTarget->aHeight || ( sX1 < 0 && sX2 < 0 ) ) {
return;
}
if ( sX1 > sX2 ) {
s32 temp = sX1;
sX1 = sX2;
sX2 = temp;
vec_t *tempv = spV1;
spV1 = spV2;
spV2 = tempv;
}
s32 x = MAX( sX1, 0 );
s32 endX = sX2;
vec4_t p1 = vertex_get_position( spV1 );
vec4_t p2 = vertex_get_position( spV2 );
f32 iz1 = p1.z;
f32 iz2 = p2.z;
if ( p1.z == 0.0f || p2.z == 0.0f ) {
return;
}
vec_t v[ MAX_VECTOR_ATTRIBUTES ];
/*
* Make a temporary because there's a coefficient that doesn't
* need to be recalculated.
*/
f32 izs1 = iz1 / ( sX2 - sX1 );
f32 izs2 = iz2 / ( sX2 - sX1 );
fragment_t f = {
.aPos = { x, sY },
};
while ( x < endX && x < ( s32 )gpRasterTarget->apTarget->aWidth ) {
/*
* Interpolate the vector values, and apply to the fragment.
*/
vec_t *pV = vertex_build_interpolated( spV1, spV2, ( f32 )( x - sX1 ) / ( sX2 - sX1 ) );
pV = vertex_scale( pV, 1 / ( ( iz1 - izs1 * ( f32 )( x - sX1 ) ) + izs2 * ( f32 )( x - sX1 ) ), V_POS );
fragment_apply( pV, &f );
/*
* Draw the vertex.
*/
memcpy( gpRasterTarget->apTarget->apData + ( sY * gpRasterTarget->apTarget->aWidth + x ), &f.aColor, sizeof( f.aColor ) );
x++;
}
}
/*
* Rasterizes a single triangle.
*
* @param void * The raw vertex data for the first vertex.
* @param void * The raw vertex data for the second vertex.
* @param void * The raw vertex data for the third vertex.
*/
void raster_rasterize_triangle( void *spV1, void *spV2, void *spV3 ) {
/*
* Extract position data and rasterize it.
*/
vec4_t p1 = vertex_get_position( spV1 );
vec4_t p2 = vertex_get_position( spV2 );
vec4_t p3 = vertex_get_position( spV3 );
/*
* Map the normalized coordinates to screen coordinates.
*/
vec2u_t v1 = {
.x = ( u32 )( ( p1.x + 1.0f ) * gpRasterTarget->apTarget->aWidth / 2 ),
.y = ( u32 )( ( p1.y + 1.0f ) * gpRasterTarget->apTarget->aHeight / 2 ),
};
vec2u_t v2 = {
.x = ( u32 )( ( p2.x + 1.0f ) * gpRasterTarget->apTarget->aWidth / 2 ),
.y = ( u32 )( ( p2.y + 1.0f ) * gpRasterTarget->apTarget->aHeight / 2 ),
};
vec2u_t v3 = {
.x = ( u32 )( ( p3.x + 1.0f ) * gpRasterTarget->apTarget->aWidth / 2 ),
.y = ( u32 )( ( p3.y + 1.0f ) * gpRasterTarget->apTarget->aHeight / 2 ),
};
/*
* In order to perform perspective correction, we need to know the
* z-coordinates of the vertices.
*/
f32 z1 = p1.z;
f32 z2 = p2.z;
f32 z3 = p3.z;
/*
* Sort the vertices by y-coordinate.
*
* y0 at the top, y1 at the middle, y2 at the bottom.
*/
if ( v1.y < v2.y ) {
vec2u_t temp = v1;
v1 = v2;
v2 = temp;
f32 tempf = z1;
z1 = z2;
z2 = tempf;
void *pTemp = spV1;
spV1 = spV2;
spV2 = pTemp;
}
if ( v2.y < v3.y ) {
vec2u_t temp = v2;
v2 = v3;
v3 = temp;
f32 tempf = z2;
z2 = z3;
z3 = tempf;
void *pTemp = spV2;
spV2 = spV3;
spV3 = pTemp;
}
if ( v1.y < v2.y ) {
vec2u_t temp = v1;
v1 = v2;
v2 = temp;
f32 tempf = z1;
z1 = z2;
z2 = tempf;
void *pTemp = spV1;
spV1 = spV2;
spV2 = pTemp;
}
/*
* If the triangle is flat, return.
*/
if ( v1.y == v3.y ) {
return;
}
/*
* Rasterize the starting y position.
*/
int y = MAX( v1.y, 0 );
y = MIN( y, gpRasterTarget->apTarget->aHeight );
/*
* Calculate the slopes of the lines.
*/
float dy0 = ( ( float )v2.x - v1.x ) / ( v2.y - v1.y );
float dy1 = ( ( float )v3.x - v1.x ) / ( v3.y - v1.y );
float dy2 = ( ( float )v3.x - v2.x ) / ( v3.y - v2.y );
u8 v0[ VERTEX_ASM_MAX_VERTEX_SIZE ];
u8 v [ VERTEX_ASM_MAX_VERTEX_SIZE ];
u8 pIA[ VERTEX_ASM_MAX_VERTEX_SIZE ];
u8 pIB[ VERTEX_ASM_MAX_VERTEX_SIZE ];
u8 pIC[ VERTEX_ASM_MAX_VERTEX_SIZE ];
/*
* Scale vertex attributes by their inverse z-coordinates.
* In the drawing process, we will then divide by the inverse
* z-coordinate again to perform perspective correction.
*/
memcpy( pIA, vertex_scale( spV1, 1 / z1, V_POS ), VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( pIB, vertex_scale( spV2, 1 / z2, V_POS ), VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( pIC, vertex_scale( spV3, 1 / z3, V_POS ), VERTEX_ASM_MAX_VERTEX_SIZE );
/*
* We'll also interpolate the z coordinate by the inverse z-coordinates.
*/
vec4_t pa = vertex_get_position( pIA );
vec4_t pb = vertex_get_position( pIB );
vec4_t pc = vertex_get_position( pIC );
pa.z = 1 / pa.z;
pb.z = 1 / pb.z;
pc.z = 1 / pc.z;
vertex_set_position( pIA, pa );
vertex_set_position( pIB, pb );
vertex_set_position( pIC, pc );
/*
* Check for flat top.
*/
if ( v1.y == v2.y ) {
/*
* Sort top two vertices by x-coordinate,
* y0 at the left, y1 at the right.
*/
if ( v1.x < v2.x ) {
vec2u_t temp = v1;
v1 = v2;
v2 = temp;
f32 tempf = z1;
z1 = z2;
z2 = tempf;
tempf = dy1;
dy1 = dy2;
dy2 = tempf;
u8 pTemp[ VERTEX_ASM_MAX_VERTEX_SIZE ];
memcpy( pTemp, pIA, VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( pIA, pIB, VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( pIB, pTemp, VERTEX_ASM_MAX_VERTEX_SIZE );
}
while ( y >= v3.y ) {
memcpy( v0, vertex_build_interpolated( pIB, pIC, ( f32 )( v1.y - y ) / ( v1.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( v, vertex_build_interpolated( pIA, pIC, ( f32 )( v1.y - y ) / ( v1.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
raster_draw_scanline( v2.x + ( y - v1.y ) * dy2, v1.x + ( y - v1.y ) * dy1, y, v0, v );
y--;
}
return;
}
/*
* Check for flat bottom.
*/
else if ( v2.y == v3.y ) {
/*
* Sort bottom two vertices by x-coordinate,
* y1 at the left, y2 at the right.
*/
if ( v2.x < v3.x ) {
vec2u_t temp = v2;
v2 = v3;
v3 = temp;
f32 tempf = z2;
z2 = z3;
z3 = tempf;
tempf = dy1;
dy1 = dy0;
dy0 = tempf;
u8 pTemp[ VERTEX_ASM_MAX_VERTEX_SIZE ];
memcpy( pTemp, pIB, VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( pIB, pIC, VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( pIC, pTemp, VERTEX_ASM_MAX_VERTEX_SIZE );
}
while ( y >= v3.y ) {
memcpy( v0, vertex_build_interpolated( pIA, pIB, ( f32 )( v1.y - y ) / ( v1.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
memcpy( v, vertex_build_interpolated( pIA, pIC, ( f32 )( v1.y - y ) / ( v1.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
raster_draw_scanline( v1.x + ( y - v1.y ) * dy0, v1.x + ( y - v1.y ) * dy1, y, v0, v );
y--;
}
return;
}
while ( y >= v3.y ) {
/*
* Bend is on the left.
*/
if ( v2.x < v3.x ) {
memcpy( v, vertex_build_interpolated( pIA, pIC, ( f32 )( v1.y - y ) / ( v1.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
if ( y >= v2.y ) {
memcpy( v0, vertex_build_interpolated( pIA, pIB, ( f32 )( v1.y - y ) / ( v1.y - v2.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
raster_draw_scanline( v1.x + ( y - v1.y ) * dy0, v1.x + ( y - v1.y ) * dy1, y, v0, v );
}
else {
memcpy( v0, vertex_build_interpolated( pIB, pIC, ( f32 )( v2.y - y ) / ( v2.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
raster_draw_scanline( v2.x + ( y - v2.y ) * dy2, v1.x + ( y - v1.y ) * dy1, y, v0, v );
}
}
/*
* Bend is on the right.
*/
else {
memcpy( v0, vertex_build_interpolated( pIA, pIC, ( f32 )( v1.y - y ) / ( v1.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
if ( y >= v2.y ) {
memcpy( v, vertex_build_interpolated( pIA, pIB, ( f32 )( v1.y - y ) / ( v1.y - v2.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
raster_draw_scanline( v1.x + ( y - v1.y ) * dy1, v1.x + ( y - v1.y ) * dy0, y, v0, v );
}
else {
memcpy( v, vertex_build_interpolated( pIB, pIC, ( f32 )( v2.y - y ) / ( v2.y - v3.y ) ), VERTEX_ASM_MAX_VERTEX_SIZE );
raster_draw_scanline( v1.x + ( y - v1.y ) * dy1, v2.x + ( y - v2.y ) * dy2, y, v0, v );
}
}
y--;
}
} |
p0lyh3dron/chik | src/modules/gfx/gfx.c | <filename>src/modules/gfx/gfx.c
/*
* gfx.c -- source file for the main graphics functions.
*
* Authored by Karl "p0lyh3dron" Kreuze on March 20, 2022
*
* This file is part of the Chik Engine.
*
* This file defines the main graphics functions. These functions
* don't require a header file, as they will compiled into the dll
* and exported to the game.
*/
#include "libchik.h"
CHIK_MODULE( graphics_init )
#include <string.h>
#include "abstract.h"
#include "rendertarget.h"
#include "drawable.h"
#include "raster.h"
#include "vertexasm.h"
#include "cull.h"
extern rendertarget_t *gpBackBuffer;
resource_t *gpVBuffer = NULL;
resource_t *gpGResources = NULL;
/*
* Creates a camera.
*
* @return handle_t The handle to the camera.
*/
handle_t create_camera( void ) {
camera_t cam;
cam.aPosition.x = 0.0f;
cam.aPosition.y = 0.0f;
cam.aPosition.z = 0.0f;
cam.aDirection.x = 0.0f;
cam.aDirection.y = 0.0f;
cam.aNear = 0.1f;
cam.aFar = 1000.f;
cam.aFOV = 90.0f;
cam.aAspect = ( float )gpBackBuffer->apTarget->aWidth / ( float )gpBackBuffer->apTarget->aHeight;
handle_t handle = resource_add( gpGResources, &cam, sizeof( camera_t ) );
if ( handle == INVALID_HANDLE ) {
log_error( "Failed to add camera resource.\n" );
return INVALID_HANDLE;
}
return handle;
}
/*
* Sets camera position.
*
* @param handle_t The handle to the camera.
* @param vec3_t The position of the camera.
*/
void set_camera_position( handle_t sCamera, vec3_t sPosition ) {
camera_t *pCamera = resource_get( gpGResources, sCamera );
if ( pCamera == NULL ) {
log_error( "Failed to get camera resource.\n" );
return;
}
pCamera->aPosition = sPosition;
}
/*
* Sets camera direction.
*
* @param handle_t The handle to the camera.
* @param vec2_t The direction of the camera.
*/
void set_camera_direction( handle_t sCamera, vec2_t sDirection ) {
camera_t *pCamera = resource_get( gpGResources, sCamera );
if ( pCamera == NULL ) {
log_error( "Failed to get camera resource.\n" );
return;
}
pCamera->aDirection = sDirection;
}
/*
* Sets camera FOV.
*
* @param handle_t The handle to the camera.
* @param float The FOV of the camera.
*/
void set_camera_fov( handle_t sCamera, float sFov ) {
camera_t *pCamera = resource_get( gpGResources, sCamera );
if ( pCamera == NULL ) {
log_error( "Failed to get camera resource.\n" );
return;
}
pCamera->aFOV = sFov;
}
/*
* Sets the global camera.
*
* @param handle_t The handle to the camera.
*/
void set_camera( handle_t sCamera ) {
gpCamera = resource_get( gpGResources, sCamera );
if ( gpCamera == NULL ) {
log_error( "Failed to get camera resource.\n" );
return;
}
}
/*
* Returns the camera's view matrix.
*
* @param handle_t The handle to the camera.
*
* @return mat4_t The view matrix.
*/
mat4_t get_camera_view( handle_t sCamera ) {
camera_t *pCamera = resource_get( gpGResources, sCamera );
if ( pCamera == NULL ) {
log_error( "Failed to get camera resource.\n" );
return m4_identity();
}
return camera_view( pCamera );
}
/*
* Returns the width and height of the screen.
*
* @return vec2_t The width and height of the screen.
*/
vec2_t get_screen_size( void ) {
vec2_t size;
size.x = gpBackBuffer->apTarget->aWidth;
size.y = gpBackBuffer->apTarget->aHeight;
return size;
}
static float theta = 0.f;
/*
* Draws the current frame.
*/
void draw_frame( void ) {
platform_draw_frame();
}
/*
* Creates the graphics context.
*/
void graphics_init( void ) {
gpGResources = resource_new( 1024 * 1024 );
if ( gpGResources == NULL ) {
log_error( "Failed to create graphics resource.\n" );
return;
}
cull_create_frustum();
init_drawable_resources();
raster_set_rendertarget( gpBackBuffer );
}
/*
* Cleans up the graphics subsystem.
*/
__attribute__( ( destructor ) )
void cleanup_graphics( void ) {
} |
p0lyh3dron/chik | src/modules/gfx/drawable.c | <reponame>p0lyh3dron/chik
/*
* drawable.c -- source for general drawable functionality
*
* Authored by Karl "p0lyh3dron" Kreuze on June 7, 2022.
*
* This file is part of the Chik engine.
*
* The usage defined here is for drawables defined in the header.
*/
#include "drawable.h"
#include "camera.h"
#include "vertexasm.h"
#include "raster.h"
#include "cull.h"
resource_t *gpResources = nullptr;
mempool_t *gpMempool = nullptr;
/*
* Initializes resources for below functions.
*
* @return u32 Whether or not the initialization was successful.
* 1 = success, 0 = failure.
*/
u32 init_drawable_resources() {
gpResources = resource_new( 64 * 1024 * 1000 );
gpMempool = mempool_new( 64 * 1024 * 1000 );
if ( gpResources == nullptr ) {
return 0;
}
if ( gpMempool == nullptr ) {
return 0;
}
return 1;
}
/*
* Creates a vertex buffer.
*
* @param void * The vertex data.
* @param u32 The size of the vertex data.
* @param u32 The stride of the vertex data.
* @param v_layout_t The layout of the vertex data.
*
* @return handle_t The vertex buffer.
* INVALID_HANDLE if the vertex buffer could not be created.
* The mesh should be freed with vbuffer_free().
*/
handle_t vbuffer_create( void *spVerts, u32 sSize, u32 sVStride, v_layout_t sLayout ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized." );
return INVALID_HANDLE;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized." );
return INVALID_HANDLE;
}
if ( spVerts == nullptr ) {
log_error( "Vertex data is null." );
return INVALID_HANDLE;
}
if ( sSize == 0 ) {
log_error( "Vertex data size is zero." );
return INVALID_HANDLE;
}
if ( sVStride == 0 ) {
log_error( "Vertex data stride is zero." );
return INVALID_HANDLE;
}
vbuffer_t buf = {};
buf.apData = mempool_alloc( gpMempool, sSize );
buf.aSize = sSize;
buf.aVStride = sVStride;
buf.aLayout = sLayout;
if ( buf.apData == nullptr ) {
log_error( "Could not allocate vertex buffer." );
return INVALID_HANDLE;
}
memcpy( buf.apData, spVerts, sSize );
handle_t h = resource_add( gpResources, &buf, sizeof( vbuffer_t ) );
if ( h == INVALID_HANDLE ) {
log_error( "Could not add vertex buffer to resource list." );
return INVALID_HANDLE;
}
return h;
}
/*
* Frees a vertex buffer.
*
* @param handle_t The vertex buffer to free.
*/
void vbuffer_free( handle_t sVBuffer ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized." );
return;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized." );
return;
}
if ( sVBuffer == INVALID_HANDLE ) {
log_error( "Vertex buffer is null." );
return;
}
vbuffer_t *pVBuffer = resource_get( gpResources, sVBuffer );
if ( pVBuffer == nullptr ) {
log_error( "Vertex buffer is null." );
return;
}
mempool_free( gpMempool, pVBuffer->apData );
resource_remove( gpResources, sVBuffer );
}
/*
* Creates a texture from a file.
*
* @param s8 * The path to the texture file.
* @param u32 The format of the texture.
*
* @return handle_t The texture.
*/
handle_t texture_create_from_file( s8 *spPath, u32 sFormat ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized." );
return INVALID_HANDLE;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized." );
return INVALID_HANDLE;
}
if ( spPath == nullptr ) {
log_error( "Texture path is null." );
return INVALID_HANDLE;
}
texture_t tex = {};
tex.apImage = image_create_from_file( spPath, sFormat );
if ( tex.apImage == nullptr ) {
log_error( "Could not create texture from file." );
return INVALID_HANDLE;
}
handle_t h = resource_add( gpResources, &tex, sizeof( texture_t ) );
if ( h == INVALID_HANDLE ) {
log_error( "Could not add texture to resource list." );
return INVALID_HANDLE;
}
return h;
}
/*
* Frees a texture.
*
* @param handle_t The texture to free.
*/
void texture_free( handle_t sTex ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized." );
return;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized." );
return;
}
if ( sTex == INVALID_HANDLE ) {
log_error( "Texture is null." );
return;
}
texture_t *pTex = resource_get( gpResources, sTex );
if ( pTex == nullptr ) {
log_error( "Texture is null." );
return;
}
image_free( pTex->apImage );
resource_remove( gpResources, sTex );
}
/*
* Creates a mesh.
*
* @param handle_t The vertex buffer.
* @param handle_t The texture.
*
* @return handle_t The mesh.
*/
handle_t mesh_create( handle_t sVBuffer, handle_t sTex ) {
mesh_t mesh = {};
mesh.aVBuf = sVBuffer;
mesh.aTex = sTex;
handle_t h = resource_add( gpResources, &mesh, sizeof( mesh_t ) );
if ( h == INVALID_HANDLE ) {
log_error( "Could not add mesh to resource list." );
return INVALID_HANDLE;
}
return h;
}
/*
* Sets the vertex buffer of a mesh.
*
* @param handle_t The mesh.
* @param handle_t The vertex buffer.
*/
void mesh_set_vertex_buffer( handle_t sMesh, handle_t sVBuffer ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized." );
return;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized." );
return;
}
if ( sMesh == INVALID_HANDLE ) {
log_error( "Mesh is null." );
return;
}
if ( sVBuffer == INVALID_HANDLE ) {
log_error( "Vertex buffer is null." );
return;
}
mesh_t *pMesh = resource_get( gpResources, sMesh );
if ( pMesh == nullptr ) {
log_error( "Mesh is null." );
return;
}
vbuffer_t *pVBuffer = resource_get( gpResources, sVBuffer );
if ( pVBuffer == nullptr ) {
log_error( "Vertex buffer is null." );
return;
}
pMesh->aVBuf = sVBuffer;
}
/*
* Sets the texture of a mesh.
*
* @param handle_t The mesh.
* @param handle_t The texture.
*/
void mesh_set_texture( handle_t sMesh, handle_t sTex ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized.\n" );
return;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized.\n" );
return;
}
if ( sMesh == INVALID_HANDLE ) {
log_error( "Mesh is null.\n" );
return;
}
if ( sTex == INVALID_HANDLE ) {
log_error( "Texture is null.\n" );
return;
}
mesh_t *pMesh = resource_get( gpResources, sMesh );
if ( pMesh == nullptr ) {
log_error( "Mesh is null.\n" );
return;
}
pMesh->aTex = sTex;
}
vec3_t gMeshTranslate = { 0.f, 0.f, 0.f };
vec3_t gMeshRotate = { 0.f, 0.f, 0.f };
/*
* Translates a mesh.
*
* @param vec3_t The translation vector.
*/
void mesh_translate( vec3_t sTranslation ) {
gMeshTranslate = sTranslation;
}
/*
* Rotates a mesh.
*
* @param vec3_t The rotation vector.
*/
void mesh_rotate( vec3_t sRotation ) {
gMeshRotate = sRotation;
}
/*
* Draws a vertex buffer.
*
* @param handle_t The handle to the vertex buffer.
*/
void vbuffer_draw( handle_t sBuffer ) {
if ( gpCamera == nullptr ) {
log_error( "No camera.\n" );
return;
}
vbuffer_t *pBuf = resource_get( gpResources, sBuffer );
if ( pBuf == nullptr ) {
log_error( "Failed to get vertex resource.\n" );
return;
}
mat4_t view = camera_view( gpCamera );
u32 numVerts = pBuf->aSize / pBuf->aVStride;
vertexasm_set_layout( pBuf->aLayout );
for ( u32 i = 0; i < numVerts; i += 3 ) {
u8 a0[ VERTEX_ASM_MAX_VERTEX_SIZE ];
u8 b0[ VERTEX_ASM_MAX_VERTEX_SIZE ];
u8 c0[ VERTEX_ASM_MAX_VERTEX_SIZE ];
/*
* Copy the vertex data into a buffer.
*/
memcpy( a0, pBuf->apData + ( i + 0 ) * pBuf->aVStride, pBuf->aVStride );
memcpy( b0, pBuf->apData + ( i + 1 ) * pBuf->aVStride, pBuf->aVStride );
memcpy( c0, pBuf->apData + ( i + 2 ) * pBuf->aVStride, pBuf->aVStride );
/*
* Get the positions of the vertices.
*/
vec4_t pa = vertex_get_position( a0 );
vec4_t pb = vertex_get_position( b0 );
vec4_t pc = vertex_get_position( c0 );
/*
* Transform the positions.
*
* If we have an active translation/rotation, apply it.
*/
mat4_t ta = m4_mul_v4( m4_rotate( gMeshRotate.x, ( vec3_t ){ 1.f, 0.f, 0.f } ), pa );
ta = m4_mul_m4( m4_rotate( gMeshRotate.y, ( vec3_t ){ 0.f, 1.f, 0.f } ), ta );
ta = m4_mul_m4( m4_rotate( gMeshRotate.z, ( vec3_t ){ 0.f, 0.f, 1.f } ), ta );
ta = m4_mul_m4( m4_translate( gMeshTranslate ), ta );
mat4_t tb = m4_mul_v4( m4_rotate( gMeshRotate.x, ( vec3_t ){ 1.f, 0.f, 0.f } ), pb );
tb = m4_mul_m4( m4_rotate( gMeshRotate.y, ( vec3_t ){ 0.f, 1.f, 0.f } ), tb );
tb = m4_mul_m4( m4_rotate( gMeshRotate.z, ( vec3_t ){ 0.f, 0.f, 1.f } ), tb );
tb = m4_mul_m4( m4_translate( gMeshTranslate ), tb );
mat4_t tc = m4_mul_v4( m4_rotate( gMeshRotate.x, ( vec3_t ){ 1.f, 0.f, 0.f } ), pc );
tc = m4_mul_m4( m4_rotate( gMeshRotate.y, ( vec3_t ){ 0.f, 1.f, 0.f } ), tc );
tc = m4_mul_m4( m4_rotate( gMeshRotate.z, ( vec3_t ){ 0.f, 0.f, 1.f } ), tc );
tc = m4_mul_m4( m4_translate( gMeshTranslate ), tc );
mat4_t ma = m4_mul_m4( view, ta );
mat4_t mb = m4_mul_m4( view, tb );
mat4_t mc = m4_mul_m4( view, tc );
/*
* Update the vertex data.
*/
vertex_set_position( a0, ( vec4_t ){ ma.v[ 0 ], ma.v[ 4 ], ma.v[ 8 ], ma.v[ 12 ] } );
vertex_set_position( b0, ( vec4_t ){ mb.v[ 0 ], mb.v[ 4 ], mb.v[ 8 ], mb.v[ 12 ] } );
vertex_set_position( c0, ( vec4_t ){ mc.v[ 0 ], mc.v[ 4 ], mc.v[ 8 ], mc.v[ 12 ] } );
/*
* If the vertex is outside of the view frustum, use
* linear interpolation to find the point on the triangle
* that is inside the view frustum.
*/
s32 numVertices = 0;
u8 *pVerts = cull_clip_triangle( a0, b0, c0, &numVertices );
/*
* Draw the clipped vertices.
*/
for ( s64 i = 0; i < numVertices - 2; ++i ) {
memcpy( a0, pVerts + ( 0 + 0 ) * VERTEX_ASM_MAX_VERTEX_SIZE, pBuf->aVStride );
memcpy( b0, pVerts + ( i + 1 ) * VERTEX_ASM_MAX_VERTEX_SIZE, pBuf->aVStride );
memcpy( c0, pVerts + ( i + 2 ) * VERTEX_ASM_MAX_VERTEX_SIZE, pBuf->aVStride );
/*
* Transform the vertex to screen space.
*/
pa = vertex_get_position( a0 );
pb = vertex_get_position( b0 );
pc = vertex_get_position( c0 );
pa.x /= pa.w;
pa.y /= pa.w;
pb.x /= pb.w;
pb.y /= pb.w;
pc.x /= pc.w;
pc.y /= pc.w;
vertex_set_position( a0, pa );
vertex_set_position( b0, pb );
vertex_set_position( c0, pc );
/*
* Draw the triangle.
*/
raster_rasterize_triangle( a0, b0, c0 );
}
}
}
/*
* Draws a mesh.
*
* @param handle_t The mesh.
*/
void mesh_draw( handle_t sMesh ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized." );
return;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized." );
return;
}
if ( sMesh == INVALID_HANDLE ) {
log_error( "Mesh is null.\n" );
return;
}
mesh_t *pMesh = resource_get( gpResources, sMesh );
if ( pMesh == nullptr ) {
log_error( "Mesh is null." );
return;
}
texture_t *pTex = resource_get( gpResources, pMesh->aTex );
if ( pTex == nullptr ) {
log_error( "Texture is null." );
return;
}
image_t *pImage = pTex->apImage;
if ( pImage == nullptr ) {
log_error( "Image is null." );
return;
}
vertexasm_bind_uniform( pTex );
vbuffer_draw( pMesh->aVBuf );
}
/*
* Frees a mesh.
*
* @param handle_t The mesh to free.
*/
void mesh_free( handle_t sMesh ) {
if ( gpResources == nullptr ) {
log_error( "Resources not initialized." );
return;
}
if ( gpMempool == nullptr ) {
log_error( "Memory pool not initialized." );
return;
}
if ( sMesh == INVALID_HANDLE ) {
log_error( "Mesh is null." );
return;
}
resource_remove( gpResources, sMesh );
} |
fbucafusco/freertos_cpp_uart | src/protocol.c | <gh_stars>0
/*
Copyright 2021, <NAME>
All rights reserved.
licence: see LICENCE file
*/
#include "FreeRTOS.h"
#include "FreeRTOSConfig.h"
#include "protocol.h"
#include "semphr.h"
#include "task.h"
/* private objects */
uartMap_t uart_used;
SemaphoreHandle_t new_frame_signal;
char* buffer;
uint16_t max_idx;
uint16_t index; //<-- index of the buffer. It points to the next free position
/**
@brief RX handler for SAPI UART Driver
@param not_used
*/
void protocol_rx_event( void *not_used )
{
( void* ) not_used;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
bool signal_app = false;
/* read the received byte */
char c = uartRxRead( UART_USB );
uint32_t mask = taskENTER_CRITICAL_FROM_ISR();
/* do something with if the app is waiting for a frame. If not, do not nothing. */
if( buffer != NULL )
{
if( max_idx - 1 == index )
{
/* restarts the frame */
index = 0;
}
if( c=='>' )
{
if( index==0 )
{
/* 1st byte */
}
else
{
/* restarts the frame (discarding the current progress)*/
index = 0;
}
buffer[index] = c;
index++;
}
else if( c=='<' )
{
/* close the frame just if at least one byte was received */
if( index >=1 )
{
/* frame ended - store the byte */
buffer[index] = c;
index++;
/* mark to signal the app */
signal_app = true;
}
else
{
/* byte discarded */
}
}
else
{
/* close the frame just if at least one byte was received */
if( index>=1 )
{
/* keep the data */
buffer[index] = c;
index++;
}
else
{
/* byte discarded */
}
}
}
taskEXIT_CRITICAL_FROM_ISR( mask );
if( signal_app )
{
/* signal the app */
xSemaphoreGiveFromISR( new_frame_signal, &xHigherPriorityTaskWoken );
}
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
/**
@brief Inicializa el stack
@param uart
@param baudRate
*/
void procotol_x_init( uartMap_t uart, uint32_t baudRate )
{
taskENTER_CRITICAL();
uart_used = uart;
/* Inicializar la UART_USB junto con las interrupciones de Tx y Rx */
uartConfig( uart, baudRate );
/* Habilito todas las interrupciones de UART_USB */
uartInterrupt( uart, true );
max_idx = 0;
buffer = NULL;
index = 0;
taskEXIT_CRITICAL();
new_frame_signal = xSemaphoreCreateBinary();
}
/**
@brief Waits for a new frame to be received. Blocks the caller task.
*/
uint16_t protocol_wait_frame( char* data, uint16_t max_size )
{
/* configure the private data to allo the RX processs. */
taskENTER_CRITICAL();
max_idx = max_size;
buffer = data;
index = 0;
/* limpio cualquier interrupcion que hay ocurrido durante el procesamiento */
uartClearPendingInterrupt( uart_used );
/* habilito isr rx de UART_USB */
uartCallbackSet( uart_used, UART_RECEIVE, protocol_rx_event, NULL );
taskEXIT_CRITICAL();
/* waits for the isr signalling */
xSemaphoreTake( new_frame_signal, portMAX_DELAY );
taskENTER_CRITICAL();
/* disable the isr until the app releases it again waiting for a new frame */
uartCallbackClr( uart_used, UART_RECEIVE );
/* prepare the return value */
uint16_t rv = index;
max_idx = 0;
buffer = NULL;
index = 0;
taskEXIT_CRITICAL();
return rv;
}
|
fbucafusco/freertos_cpp_uart | inc/protocol.h | <filename>inc/protocol.h<gh_stars>0
/*
Copyright 2021, <NAME>
All rights reserved.
licence: see LICENCE file
*/
#ifndef PROTOCOL_H_
#define PROTOCOL_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "sapi.h"
void procotol_x_init( uartMap_t uart, uint32_t baudRate );
uint16_t protocol_wait_frame( char* data, uint16_t max_size );
#ifdef __cplusplus
}
#endif
#endif |
osadalakmal/hyperscan-cpp-wrapper | hs_wrapper.h | <reponame>osadalakmal/hyperscan-cpp-wrapper<filename>hs_wrapper.h
#ifndef HS_WRAPPER_H_DEFINED
#define HS_WRAPPER_H_DEFINED
#include <hs/hs.h>
#include <memory>
#include <string>
#include <vector>
class HyperScanDatabase {
public:
typedef match_event_handler EventHandler;
enum class ScanMode {
BLOCK,
STREAM
};
HyperScanDatabase(ScanMode scanMode);
~HyperScanDatabase();
int addPattern(const char* pattern, int flags);
int scan(const char* data, size_t dataSize, EventHandler);
private:
std::vector<char*> m_patterns;
std::vector<unsigned int> m_flags;
std::vector<unsigned int> m_ids;
bool m_compiled = false;
ScanMode m_scanMode;
hs_database_t* m_database;
hs_scratch_t* m_scratch;
};
#endif // HS_WRAPPER_H_DEFINED |
eaplatanios/swift-language | include/swift/SIL/SILWitnessVisitor.h | <filename>include/swift/SIL/SILWitnessVisitor.h
//===--- SILWitnessVisitor.h - Witness method table visitor -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the SILWitnessVisitor class, which is used to generate and
// perform lookups in witness method tables for protocols and protocol
// conformances.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SIL_SILWITNESSVISITOR_H
#define SWIFT_SIL_SILWITNESSVISITOR_H
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ProtocolAssociations.h"
#include "swift/AST/Types.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/Support/ErrorHandling.h"
namespace swift {
/// A CRTP class for visiting the witnesses of a protocol.
///
/// The design here is that each entry (or small group of entries)
/// gets turned into a call to the implementation class describing
/// the exact variant of witness. For example, for member
/// variables, there should be separate callbacks for adding a
/// getter/setter pair, for just adding a getter, and for adding a
/// physical projection (if we decide to support that).
///
/// You must override the following methods:
/// - addOutOfLineBaseProtocol()
/// - addMethod()
/// - addConstructor()
/// - addAssociatedType()
template <class T> class SILWitnessVisitor : public ASTVisitor<T> {
T &asDerived() { return *static_cast<T*>(this); }
public:
void visitProtocolDecl(ProtocolDecl *protocol) {
// The protocol conformance descriptor gets added first.
asDerived().addProtocolConformanceDescriptor();
for (const auto &reqt : protocol->getRequirementSignature()) {
switch (reqt.getKind()) {
// These requirements don't show up in the witness table.
case RequirementKind::Superclass:
case RequirementKind::SameType:
case RequirementKind::Layout:
continue;
case RequirementKind::Conformance: {
auto type = reqt.getFirstType()->getCanonicalType();
assert(type->isTypeParameter());
auto requirement =
cast<ProtocolType>(reqt.getSecondType()->getCanonicalType())
->getDecl();
// ObjC protocols do not have witnesses.
if (!Lowering::TypeConverter::protocolRequiresWitnessTable(requirement))
continue;
// If the type parameter is 'self', consider this to be protocol
// inheritance. In the canonical signature, these should all
// come before any protocol requirements on associated types.
if (auto parameter = dyn_cast<GenericTypeParamType>(type)) {
assert(type->isEqual(protocol->getSelfInterfaceType()));
assert(parameter->getDepth() == 0 && parameter->getIndex() == 0 &&
"non-self type parameter in protocol");
asDerived().addOutOfLineBaseProtocol(requirement);
continue;
}
// Otherwise, add an associated requirement.
AssociatedConformance assocConf(protocol, type, requirement);
asDerived().addAssociatedConformance(assocConf);
continue;
}
}
llvm_unreachable("bad requirement kind");
}
// Add the associated types.
for (auto *associatedType : protocol->getAssociatedTypeMembers()) {
// If this is a new associated type (which does not override an
// existing associated type), add it.
if (associatedType->getOverriddenDecls().empty())
asDerived().addAssociatedType(AssociatedType(associatedType));
}
if (asDerived().shouldVisitRequirementSignatureOnly())
return;
// Visit the witnesses for the direct members of a protocol.
for (Decl *member : protocol->getMembers()) {
ASTVisitor<T>::visit(member);
}
}
/// If true, only the base protocols and associated types will be visited.
/// The base implementation returns false.
bool shouldVisitRequirementSignatureOnly() const {
return false;
}
/// Fallback for unexpected protocol requirements.
void visitDecl(Decl *d) {
llvm_unreachable("unhandled protocol requirement");
}
void visitAbstractStorageDecl(AbstractStorageDecl *sd) {
sd->visitOpaqueAccessors([&](AccessorDecl *accessor) {
// SWIFT_ENABLE_TENSORFLOW
addMethodAndAutoDiffAssociatedMethodsIfRequired(accessor,
SILDeclRef::Kind::Func);
});
}
void visitConstructorDecl(ConstructorDecl *cd) {
// SWIFT_ENABLE_TENSORFLOW
addMethodAndAutoDiffAssociatedMethodsIfRequired(
cd, SILDeclRef::Kind::Allocator);
}
void visitAccessorDecl(AccessorDecl *func) {
// Accessors are emitted by visitAbstractStorageDecl, above.
}
void visitFuncDecl(FuncDecl *func) {
assert(!isa<AccessorDecl>(func));
// SWIFT_ENABLE_TENSORFLOW
addMethodAndAutoDiffAssociatedMethodsIfRequired(func,
SILDeclRef::Kind::Func);
}
void visitMissingMemberDecl(MissingMemberDecl *placeholder) {
asDerived().addPlaceholder(placeholder);
}
void visitAssociatedTypeDecl(AssociatedTypeDecl *td) {
// We already visited these in the first pass.
}
void visitTypeAliasDecl(TypeAliasDecl *tad) {
// We don't care about these by themselves for witnesses.
}
void visitPatternBindingDecl(PatternBindingDecl *pbd) {
// We only care about the contained VarDecls.
}
void visitIfConfigDecl(IfConfigDecl *icd) {
// We only care about the active members, which were already subsumed by the
// enclosing type.
}
void visitPoundDiagnosticDecl(PoundDiagnosticDecl *pdd) {
// We don't care about diagnostics at this stage.
}
// SWIFT_ENABLE_TENSORFLOW
private:
void addMethodAndAutoDiffAssociatedMethodsIfRequired(
AbstractFunctionDecl *func, SILDeclRef::Kind kind) {
if (!SILDeclRef::requiresNewWitnessTableEntry(func))
return;
auto funcDeclRef = SILDeclRef(func, kind);
asDerived().addMethod(funcDeclRef);
for (auto *DA : func->getAttrs().getAttributes<DifferentiableAttr>()) {
asDerived().addMethod(funcDeclRef.asAutoDiffAssociatedFunction(
AutoDiffAssociatedFunctionIdentifier::get(
AutoDiffAssociatedFunctionKind::JVP, /*differentiationOrder*/ 1,
DA->getParameterIndices(), func->getASTContext())));
asDerived().addMethod(funcDeclRef.asAutoDiffAssociatedFunction(
AutoDiffAssociatedFunctionIdentifier::get(
AutoDiffAssociatedFunctionKind::VJP, /*differentiationOrder*/ 1,
DA->getParameterIndices(), func->getASTContext())));
}
}
};
} // end namespace swift
#endif
|
eaplatanios/swift-language | lib/SILOptimizer/Mandatory/Differentiation.h | <reponame>eaplatanios/swift-language
//===--- Differentiation.h - SIL Automatic Differentiation ----*- C++ -*---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// SWIFT_ENABLE_TENSORFLOW
//
// Reverse-mode automatic differentiation utilities.
//
// NOTE: Although the AD feature is developed as part of the Swift for
// TensorFlow project, it is completely independent from TensorFlow support.
//
// TODO: Move definitions here from Differentiation.cpp.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SILOPTIMIZER_MANDATORY_DIFFERENTIATION_H
#define SWIFT_SILOPTIMIZER_MANDATORY_DIFFERENTIATION_H
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Utils/Local.h"
namespace swift {
using llvm::DenseMap;
using llvm::SmallDenseMap;
using llvm::SmallDenseSet;
using llvm::SmallMapVector;
using llvm::SmallSet;
/// Helper class for visiting basic blocks in post-order post-dominance order,
/// based on a worklist algorithm.
class PostOrderPostDominanceOrder {
SmallVector<DominanceInfoNode *, 16> buffer;
PostOrderFunctionInfo *postOrderInfo;
size_t srcIdx = 0;
public:
/// Constructor.
/// \p root The root of the post-dominator tree.
/// \p postOrderInfo The post-order info of the function.
/// \p capacity Should be the number of basic blocks in the dominator tree to
/// reduce memory allocation.
PostOrderPostDominanceOrder(DominanceInfoNode *root,
PostOrderFunctionInfo *postOrderInfo,
int capacity = 0)
: postOrderInfo(postOrderInfo) {
buffer.reserve(capacity);
buffer.push_back(root);
}
/// Get the next block from the worklist.
DominanceInfoNode *getNext() {
if (srcIdx == buffer.size())
return nullptr;
return buffer[srcIdx++];
}
/// Pushes the dominator children of a block onto the worklist in post-order.
void pushChildren(DominanceInfoNode *node) {
pushChildrenIf(node, [](SILBasicBlock *) { return true; });
}
/// Conditionally pushes the dominator children of a block onto the worklist
/// in post-order.
template <typename Pred>
void pushChildrenIf(DominanceInfoNode *node, Pred pred) {
SmallVector<DominanceInfoNode *, 4> children;
for (auto *child : *node)
children.push_back(child);
llvm::sort(children.begin(), children.end(),
[&](DominanceInfoNode *n1, DominanceInfoNode *n2) {
return postOrderInfo->getPONumber(n1->getBlock()) <
postOrderInfo->getPONumber(n2->getBlock());
});
for (auto *child : children) {
SILBasicBlock *childBB = child->getBlock();
if (pred(childBB))
buffer.push_back(child);
}
}
};
} // end namespace swift
#endif // SWIFT_SILOPTIMIZER_MANDATORY_DIFFERENTIATION_H
|
RolandWH/ccolour | example.c | /* File: example.c
Author: <NAME> (<EMAIL>)
Desc: Example file to demonstrate usage of colour.h (ccolour)
License: MIT License (../LICENSE)
*/
#include "colour.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
void rainbow()
{
const char COLOURS[8][7] =
{ "BLACK", "RED", "GREEN", "YELLOW", "BLUE", "PURPLE", "CYAN", "WHITE" };
for (int fg = 0; fg < 8; fg++)
{
for (int bg = 0; bg < 8; bg++)
{
char msg[18];
snprintf(msg, 18, "%s ON %s\n", COLOURS[fg], COLOURS[bg]);
ChangeColour(msg, bg + 40, fg + 30, true);
}
}
}
int main()
{
ChangeColour(
"ERROR: This is a big scary error\n",
RED_FOREGROUND,
DEFAULT_COLOR,
true
);
ChangeColour(
"Yellow warning text\n",
YELLOW_FOREGROUND,
DEFAULT_COLOR,
true
);
ChangeColour(
"White text on blue background\n",
WHITE_FOREGROUND,
BLUE_BACKGROUND,
true
);
char choice[16];
printf("Are you ready for the rainbow? [HELL YEAH / NO IM SCARED]\n");
fgets(choice, 16, stdin);
// strcmp returns false (0) when a match IS found
if (!strcmp(choice, "HELL YEAH\n"))
{
rainbow();
}
else if (!strcmp(choice, "NO IM SCARED\n"))
{
ChangeColour("YOU COWARD\n", RED_FOREGROUND, DEFAULT_COLOR, true);
}
return 0;
}
|
RolandWH/ccolour | colour.h | /* File: colour.h
Author: <NAME> (<EMAIL>)
Desc: Contains function for manipulating colour on ANSI terminals
License: MIT License (../LICENSE)
*/
#pragma once
#define DEFAULT_COLOR 0
#define BLACK_FOREGROUND 30
#define RED_FOREGROUND 31
#define GREEN_FOREGROUND 32
#define YELLOW_FOREGROUND 33
#define BLUE_FOREGROUND 34
#define PURPLE_FOREGROUND 35
#define CYAN_FOREGROUND 36
#define WHITE_FOREGROUND 37
#define BLACK_BACKGROUND 40
#define RED_BACKGROUND 41
#define GREEN_BACKGROUND 42
#define YELLOW_BACKGROUND 43
#define BLUE_BACKGROUND 44
#define PURPLE_BACKGROUND 45
#define CYAN_BACKGROUND 46
#define WHITE_BACKGROUND 47
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif // _WIN32
#include <stdbool.h>
#include <stdio.h>
/* Structure of colour change string:
1. Escape sequence for changing colour (\33)
2. Opening bracket ( [ )
3. Foreground colour (%d, fg)
4. Semicolon (;)
5. Background colour (%d, bg)
6. Character to end colour changing (m)
7. Message passed to function (%s, msg)
8. Newline (\n)
If only one colour is being changed then the semicolon is left out
Example for red text on black background:
"\33[31;40m"
*/
static void ChangeColour(const char* msg, int fg, int bg, bool revert)
{
// Enable ANSI support on Windows
#ifdef _WIN32
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hOut, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hOut, dwMode);
#endif // _WIN32
if (!bg)
{
printf("\33[%dm%s", fg, msg);
}
else if (!fg)
{
printf("\33[%dm%s", bg, msg);
}
else
{
printf("\33[%d;%dm%s", fg, bg, msg);
}
if (revert) printf("\33[%dm", DEFAULT_COLOR);
}
|
A200K/SkypeAdBlocker | Skype AdBlocker/Utils.h | #ifndef _UTILS_H
#define _UTILS_H
#include <Windows.h>
void *DetourFunction( void *pLocation, void *pDetour, size_t ulLength );
#endif |
JosephPena1/Battle-Arena | raygame/Enemy.h | <filename>raygame/Enemy.h
#pragma once
#include "Actor.h"
class Enemy
: public Actor
{
public:
Enemy() : Actor() {};
Enemy(float x, float y, float health, float collisionRadius, const char* spriteFilePath, float maxSpeed, Actor* target);
bool detectTarget(float maxAngle, float maxDistance);
void update(float deltatime) override;
void debug() override;
void draw() override;
static void createEnemies(int enemyCount, Actor* target);
void setEnemyCounter(int count);
void setTarget(Actor* target);
void onCollision(Actor* other) override;
void takeDamage();
protected:
void updateFacing() override;
//Enemy** m_enemies;
private:
Actor* m_target;
}; |
JosephPena1/Battle-Arena | raygame/Bullet.h | <reponame>JosephPena1/Battle-Arena
#pragma once
#include "Actor.h"
class Bullet : public Actor
{
public:
Bullet() : Actor() {};
Bullet(float x, float y, float collisionRadius, const char* spriteFilePath, float maxSpeed, MathLibrary::Vector2 velocity);
void update(float deltaTime) override;
void draw() override;
protected:
void updateFacing() override;
void onCollision(Actor* other) override;
};
|
JosephPena1/Battle-Arena | raygame/Player.h | <reponame>JosephPena1/Battle-Arena
#pragma once
#include "Actor.h"
class Player
: public Actor
{
public:
Player() : Actor() {};
Player(float x, float y, float health, float collisionRadius, const char* spriteFilePath, float maxSpeed);
void update(float deltatime) override;
void debug() override;
void draw() override;
void onCollision(Actor* other) override;
void takeDamage();
protected:
void updateFacing() override;
private:
float m_immuneFrames;
float m_immuneTime;
}; |
AndrewAndreev/mainarray | main.c | #include <stdio.h>
const void *ptrprintf = printf;
#pragma section(".exre", execute, read)
__declspec(allocate(".exre")) int main[] =
{
0x646C6890, 0x20680021, 0x68726F57,
0x2C6F6C6C, 0x48000068, 0x24448D65,
0x15FF5002, &ptrprintf, 0xC314C483
};
|
kajun1337/libft | ft_memcpy.c | <reponame>kajun1337/libft<filename>ft_memcpy.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memcpy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:12:41 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:19:20 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_memcpy(void *dest, const void *src, size_t n)
{
unsigned char *str1;
const unsigned char *str2;
if (!dest && !src)
return (0);
str1 = dest;
str2 = src;
while (n-- > 0)
{
*str1++ = *str2++;
}
return (dest);
}
/*
src hafıza bölgesinden n byte ı dst hafıza bölgesine kopyalar.
dst ve src çakışırsa tanımsız olur.
*/
|
kajun1337/libft | ft_calloc.c | <filename>ft_calloc.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_calloc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:08:27 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:28:51 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_calloc(size_t count, size_t size)
{
void *mem;
mem = malloc(count * size);
if (!mem)
return (NULL);
ft_memset(mem, 0, (count * size));
return (mem);
}
/*
count nesneleri için bitişik olarak yeterli hafıza tahsis eder ve
bir pointer döndürür.
bu alan sıfır değeri byte ı ile doldurulur.
size atayacağımız değişkenin türüne göre değişir. mesela charsa
size 1 olur int ise
size 2 olur.count ise sayısı yani iki tane char tipi değişken
için ayıracağımız alan 2*1 olacak.
ayırdığımız hafıza alanını byte a attık ve bu alanları null ile doldurduk.
bize null ile doldurulmuş byte pointerının adresini dönüş yaptı.
malloc sadece yer ayırır , ayırdığı yerin null olduğu garantisini vermez.
calloc yer ayırır ve orayı null yapar
*/
|
kajun1337/libft | ft_strmapi.c | <reponame>kajun1337/libft
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strmapi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:17:16 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:34:35 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strmapi(char const *s, char (*f)(unsigned int, char))
{
char *res;
int i;
if (!s)
return (NULL);
i = 0;
res = ft_strdup(s);
if (!res)
return (NULL);
while (res[i])
{
res[i] = f(i, res[i]);
i++;
}
return (res);
}
/*
/f fonksiyonunu s stringinin her bir karakterine uygular
ve mallocla yer ayırdığımız str ye bu elemanları gönderir
str ye s nin elemanlarının f fonksiyonu uygulanmış halini gönderiyoruz 28
*/
|
kajun1337/libft | ft_lstnew.c | <gh_stars>1-10
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstnew.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:11:55 by muhozkan #+# #+# */
/* Updated: 2022/02/19 16:11:58 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lstnew(void *content)
{
t_list *new_list;
new_list = malloc(sizeof(t_list));
if (!new_list)
return (NULL);
new_list->content = content;
new_list->next = NULL;
return (new_list);
}
//new_list->content = content yapmamızın sebebi
// fonksiyonda content'e gelen şeyi yazdırmak
|
kajun1337/libft | ft_itoa.c | <gh_stars>1-10
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:10:21 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:36:43 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_ff(long n)
{
size_t karakter;
karakter = 0;
if (n < 0)
{
karakter++;
n = -n;
}
while (n >= 1)
{
karakter++;
n = n / 10;
}
return (karakter);
}
static char *ft_zz(char *rtn, long nbr, int len, int neg)
{
if (nbr != 0)
rtn = malloc(sizeof(char) * (len + 1));
else
return (rtn = ft_strdup ("0"));
if (!rtn)
return (0);
if (nbr < 0)
{
neg++;
nbr = -nbr;
}
rtn[len] = '\0';
while (--len)
{
rtn[len] = (nbr % 10) + '0';
nbr = nbr / 10;
}
if (neg == 1)
rtn[0] = '-';
else
rtn[0] = (nbr % 10) + '0';
return (rtn);
}
char *ft_itoa(int n)
{
int len;
char *rtn;
long nbr;
int neg;
nbr = n;
len = ft_ff(nbr);
rtn = 0;
neg = 0;
rtn = ft_zz(rtn, nbr, len, neg);
if (!rtn)
return (0);
return (rtn);
}
// int to ascii |
kajun1337/libft | ft_memcmp.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memcmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:12:30 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:35:53 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_memcmp(const void *s1, const void *s2, size_t n)
{
size_t i;
unsigned char *us1;
unsigned char *us2;
if (n == 0)
return (0);
us1 = (unsigned char *)s1;
us2 = (unsigned char *)s2;
i = 0;
while (i < n)
{
if (us1[i] != us2[i])
return (us1[i] - us2[i]);
i++;
}
return (0);
}
/*
s1 string byte ını s2 string byte ı ile karşılaştırır. İki string uzunluğu
da n byte uzunluğunda farz edilir. İki string aynıysa sıfır döndürür
aksi takdirde ilk iki byte arasındaki farkı döndürür.
Unsigned char değerleri gibi davranır.
*/
|
kajun1337/libft | ft_strlcat.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strlcat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:16:10 by muhozkan #+# #+# */
/* Updated: 2022/02/25 22:16:21 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t ft_strlen(const char *str);
size_t ft_strlcat(char *dest, char *src, size_t size)
{
unsigned int i;
unsigned int j;
unsigned int dlen;
unsigned int slen;
i = 0;
j = 0;
while (dest[j] != '\0')
{
j++;
}
dlen = j;
slen = ft_strlen(src);
if (size == 0 || size <= dlen)
return (slen + size);
while (src[i] != '\0' && i < size - dlen - 1)
{
dest[j] = src[i];
i++;
j++;
}
dest[j] = '\0';
return (dlen + slen);
}
/*
dst nin sonuna src stringini ekler.
en fazla dstsize -strlen(dst)-1 karakter ekler.
* dstsize ın 0 olması ve dst string in dstsizedan uzun olması
(pratikte böyle bir şey olamaz ya dstsize yanlıştır ya da
dst düzgün bir string değildir)durumları hariç NULL sonlanır.
* return de destin son uzunluğu + src nin birleştiremediği kısmının
uzunluğunu dönüyor yani ikisinin en baştaki toplam uzunluğunu dönüyor. */
|
kajun1337/libft | ft_strtrim.c | <reponame>kajun1337/libft
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:17:58 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:33:58 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_trim_start(const char *s, const char *set)
{
int i;
int j;
j = 0;
while (s[j])
{
i = 0;
while (set[i])
{
if (s[j] == set[i])
{
j++;
break ;
}
i++;
}
if (!set[i])
break ;
}
return (j);
}
static int ft_trim_end(const char *s, const char *set)
{
int i;
int j;
i = ft_strlen(s) - 1;
while (s[i])
{
j = 0;
while (set[j])
{
if (s[i] == set[j])
{
i--;
break ;
}
j++;
}
if (!set[j])
break ;
}
return (i);
}
char *ft_strtrim(const char *s, const char *set)
{
int i;
int j;
int index;
char *ptr;
ptr = NULL;
if (s && set)
{
i = ft_trim_end(s, set);
j = ft_trim_start(s, set);
if (i < j)
return (ft_strdup(""));
ptr = malloc(sizeof(char) * ((i + 1) - j + 1));
if (!ptr)
return (NULL);
index = 0;
while (j <= i)
{
ptr[index] = s[j];
index++;
j++;
}
ptr[index] = '\0';
}
return (ptr);
}
/* s stringini başındaki ve sonundaki (set içinde belirtilen)
karakterler olmadan yazar. s stringine hafızada yer tahsis eder.
* eğer başta ve sonda set yoksa direkt s stringi kopyasını döner.
* yeterli bellek yoksa fonksiyon NULL döner.
*/
|
kajun1337/libft | ft_strjoin.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strjoin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:15:57 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:35:10 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strjoin(char const *s1, char const *s2)
{
size_t index;
size_t j;
char *s3;
index = 0;
j = 0;
if (!s1 || !s2)
return (NULL);
s3 = malloc(ft_strlen(s1) + ft_strlen(s2) + 1);
if (!s3)
return (NULL);
while (s1[index])
{
s3[index] = s1[index];
index++;
}
while (s2[j])
{
s3[index++] = s2[j];
j++;
}
s3[index] = '\0';
return (s3);
}
//iki ayri stringi bir stringde birlestirir
|
kajun1337/libft | ft_strchr.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strchr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:15:24 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:35:22 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strchr(const char *str, int c)
{
size_t index;
index = 0;
while (str[index])
{
if (str[index] == (char)c)
return ((char *)&str[index]);
index++;
}
if (c == '\0')
return ((char *)(str + index));
return (NULL);
}
/*
Stringte int c yerine verdiğimiz karakterin
ilk göründüğü yeri belirler ve oradan sonra çıktı verir. */
|
kajun1337/libft | libft.h | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/17 11:50:11 by muhozkan #+# #+# */
/* Updated: 2022/02/17 11:50:22 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBFT_H
# define LIBFT_H
# include <stdio.h>
# include <unistd.h>
# include <stdlib.h>
# include <string.h>
// int
int ft_isalpha(int c);
int ft_isdigit(int c);
int ft_isalnum(int c);
int ft_isascii(int c);
int ft_isprint(int c);
int ft_tolower(int ch);
int ft_toupper(int ch);
int ft_atoi(const char *str);
int ft_strncmp(const char *s1, const char *s2, size_t n);
int ft_memcmp(const void *s1, const void *s2, size_t n);
//size_t
size_t ft_strlen(const char *c);
size_t ft_strlcat(char *dest, char *src, size_t size);
size_t ft_strlcpy(char *dest, const char *src, size_t size);
//void
void *ft_memset(void *word, int latter, size_t length);
void *ft_memcpy(void *dest, const void *src, size_t n);
void *ft_memchr(const void *ptr, int c, size_t n);
void ft_bzero(void *word, size_t length);
void *ft_calloc(size_t count, size_t size);
void *ft_memmove(void *dest, const void *src, size_t n);
void ft_putchar_fd(char c, int fd);
void ft_putstr_fd(char const *s, int fd);
void ft_putendl_fd(char const *s, int fd);
void ft_putnbr_fd(int n, int fd);
void ft_striteri(char *s, void (*f)(unsigned int, char *));
//char
char *ft_strchr(const char *str, int c);
char *ft_strrchr(const char *str, int c);
char *ft_strnstr(const char *s1, const char *s2, size_t n);
char *ft_strdup(const char *str);
char *ft_substr(char const *s, unsigned int start, size_t len);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strmapi(char const *s, char (*f) (unsigned int, char));
char *ft_strtrim(char const *s, char const *set);
char *ft_itoa(int n);
char **ft_split(char const *s, char c);
typedef struct s_list
{
void *content;
struct s_list *next;
} t_list;
t_list *ft_lstnew(void *content);
t_list *ft_lstlast(t_list *lst);
void ft_lstadd_front(t_list **lst, t_list *new);
void ft_lstadd_back(t_list **lst, t_list *new);
void ft_lstclear(t_list **lst, void (*del)(void *));
void ft_lstdelone(t_list *lst, void (*del)(void*));
void ft_lstiter(t_list *lst, void (*f)(void *));
int ft_lstsize(t_list *lst);
t_list *ft_lstmap(t_list *lst, void *(*f)(void*), void (*del)(void *));
#endif
|
kajun1337/libft | ft_strdup.c | <filename>ft_strdup.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strdup.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:15:36 by muhozkan #+# #+# */
/* Updated: 2022/02/23 14:26:32 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strdup(const char *str)
{
size_t i;
char *p1;
size_t index;
index = 0;
i = ft_strlen(str);
p1 = malloc(sizeof(char) * (i + 1));
if (!p1)
return (NULL);
while (str[index])
{
p1[index] = str[index];
index++;
}
p1[index] = '\0';
return (p1);
}
// sonuna '\0' koyabilmek icin + 1 ekledik
/*
s1 stringi için hafızada yeterli alan tahsis eder,
kopyalamayı yapar ve ona bir pointer döndürür.
* * yeterli hafıza yoksa NULL döner.
* duplicate edilecek alan için yer ayırt eder
* s1 in eleman sayısı +1 kadar.
* s1 i dup içine kopylara ve s1 in aynısından oluşmuş olur */
|
kajun1337/libft | ft_split.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:15:11 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:35:28 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_words(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
if (s[i] == c)
i++;
else
{
count++;
while (s[i] && s[i] != c)
i++;
}
}
return (count);
}
static char *ft_make_words(char *word, char const *s, int j, int word_ln)
{
int i;
i = 0;
while (word_ln > 0)
word[i++] = s[j - word_ln--];
word[i] = 0;
return (word);
}
static char **ft_split_words(char **res, char const *s, char c, int word_ct)
{
int i;
int j;
int word_ln;
i = 0;
j = 0 ;
word_ln = 0;
while (s[j] && i < word_ct)
{
while (s[j] && s[j] == c)
j++;
while (s[j] && s[j] != c)
{
j++;
word_ln++;
}
res[i] = (char *)malloc(sizeof(char) * (word_ln + 1));
if (!res[i])
return (0);
ft_make_words (res[i], s, j, word_ln);
word_ln = 0;
i++;
}
res[i] = 0;
return (res);
}
char **ft_split(char const *s, char c)
{
int word_ct;
char **res;
if (s == 0)
return (0);
word_ct = ft_count_words(s, c);
res = (char **)malloc(sizeof(char *) * (word_ct + 1));
if (!res)
return (0);
ft_split_words (res, s, c, word_ct);
return (res);
}
/*
her elemanı yazdırmasını burada a yı arttırarak sağladık.
böyle yazmazsak sadece fatma yazıp bıraktı
*/
|
kajun1337/libft | ft_memchr.c | <filename>ft_memchr.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memchr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:12:17 by muhozkan #+# #+# */
/* Updated: 2022/02/23 14:25:09 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_memchr(const void *s, int c, size_t n)
{
size_t i;
unsigned char *pts;
unsigned char cc;
pts = (void *)s;
cc = c;
i = 0;
while (i < n)
{
if ((pts[i] - cc) == 0)
return ((void *)s + i);
i++;
}
return (NULL);
}
/*
int main(void)
{
printf("%s", ft_memchr("fatma", 'm', 5));
}
verilen byte kadar kısmı kontrol edip orada aradığımız karakter var mı
diye bakar.
* aradığımız karakterden sonrasını çıktı veriri
bir stringdeki bir kelimenin bellekteki değerini döndürür */
|
kajun1337/libft | ft_strrchr.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strrchr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:17:46 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:34:06 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strrchr(const char *str, int c)
{
int i;
i = 0;
while (str[i])
{
i++;
}
while (i >= 0)
{
if (str[i] == c)
{
return (((char *)str) + i);
}
i--;
}
return (NULL);
}
// sagdan baslayarak istedigimiz harfi bulur ve kelimeyi döndürür
/*
int c yerine yazdığımız karakterin son göründüğü yeri belirler.
* s nin point ettiği ilk karakteri kaybetmemek için oraya b pointerını atıyoruz.
syi de s nin son elemanını point edecek şekilde atıyoruz.
* s pointerını c karakterine rastlayana kadar sondan başa doğru gezdiriyoruz.
* c yi bulduğunda point ettiği yerden itibaren outpu verir.
* */
|
kajun1337/libft | ft_strnstr.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strnstr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:17:37 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:34:16 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strnstr(const char *s1, const char *s2, size_t n)
{
size_t i;
size_t j;
size_t s2_len;
i = 0;
s2_len = ft_strlen(s2);
if (!s2_len)
return ((char *)s1);
if (n != 0)
{
while (s1[i] && i <= n - s2_len)
{
j = 0;
while (s2[j] && s2[j] == s1[i + j])
j++;
if (j == s2_len)
return ((char *)&s1[i]);
i++;
}
}
return (NULL);
}
// n kadar bolgede bir kelimede istenilen kelimeyi döndürür
// str kelime
// to_find aranılacak olan kelime
|
kajun1337/libft | ft_memset.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memset.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:13:05 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:35:41 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_memset(void *word, int latter, size_t length)
{
size_t index;
char *new_word;
index = 0;
new_word = (char *) word;
while (index < length)
{
new_word[index] = latter;
index++;
}
return (new_word);
}
/* verdiğimiz uzunluğa kadar olan kısmı verdiğimiz karakter ile değiştirir
*/
|
kajun1337/libft | ft_strdup_main.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strdup_main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/25 23:47:41 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:47:41 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
char *ft_strdup(const char *str);
int main(int argc, char const *argv[])
{
char orjinal_string[100] = "Fenito Cagare Resulte importante/ yani haticeye degil neticeye bak";
char *kopya_pointer;
kopya_pointer = ft_strdup(orjinal_string);
printf("%s\n", kopya_pointer);
printf("----------\n");
return 0;
}
|
kajun1337/libft | ft_strlcpy.c | <reponame>kajun1337/libft
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strlcpy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:16:51 by muhozkan #+# #+# */
/* Updated: 2022/02/23 14:26:55 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t ft_strlcpy(char *dest, const char *src, size_t size)
{
size_t index;
index = 0;
if (size > 0)
{
while (src[index] && index < (size - 1))
{
dest[index] = src[index];
index++;
}
dest[index] = '\0';
}
while (src[index])
index++;
return (index);
}
/* strlcpy ve strlcat; strncat ve strncpy fonksiyonlarına göre daha güvenli,
tutarlı ve hataya daha az meyilli olduğu için dizayn edilmiştir.
* strlcpy destsize -1 karakteri src den dst ye kopyalar. */
|
kajun1337/libft | ft_memmove.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memmove.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:12:54 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:14:21 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_memmove(void *dest, const void *src, size_t n)
{
unsigned char *d;
const unsigned char *s;
if (dest == src)
return (dest);
else if (dest < src)
dest = ft_memcpy(dest, src, n);
else
{
d = (unsigned char *)dest;
s = (const unsigned char *)src;
while (n--)
d[n] = s[n];
}
return (dest);
}
// memcpy'den farkı çakışmaları önler
/* src stringinin len byte ını dst stringine kopyalar.
Stringler çakışırsa kopyalamaya sondan başlar
böylece src yi destroy etmemiş olur. dst - src < len derken
aslında normalde kaybolacak karaktere kadar kopyalamakta sorun yok.
mesela src +3 ten itibaren src nin 2 karakterini alırsak
src yi bozmadan zaten kopyalama yapmış oluyoruz. src + 3 ten itibaren 4
karakter alsak src + 3 ten sonrasını değiştireceği için
aradakiler bozulmaya uğrar.
*/
|
kajun1337/libft | ft_substr.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muhozkan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/19 16:18:07 by muhozkan #+# #+# */
/* Updated: 2022/02/25 23:33:49 by muhozkan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_substr(char const *s, unsigned int start, size_t len)
{
size_t i;
size_t j;
char *final;
if (s)
{
if (start >= ft_strlen(s) || len == 0 || ft_strlen(s) == 0)
return (ft_strdup(""));
i = 0;
while (i < len && s[i + start] != '\0')
i++;
final = (char *) malloc((sizeof(char) * i) + 1);
if (!(final))
return (NULL);
j = 0;
while (j < i)
{
final[j] = s[start + j];
j++;
}
final[j] = '\0';
return (final);
}
return (NULL);
}
/* start indexi ile başlayan ve len uzunluğundaki alt stringi
s stringinden ayırır ve hafıza alanına atar.
*/
|
yrq110/HouseRadar | AMapDemo/TopView.h | //
// TopView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/21.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TopView : UIView
@property(strong,nonatomic)UIButton *returnButton;
@property(strong,nonatomic)UILabel *topLabel;
@end
|
yrq110/HouseRadar | AMapDemo/PicLoadEnableSharedClass.h | //
// PicLoadEnableSharedClass.h
// AMapDemo
//
// Created by yrq_mac on 16/2/16.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface PicLoadEnableSharedClass : NSObject
@property BOOL WWANLoadPicEnabled;
@property BOOL MobileNetLoadEnabled;
@property BOOL isWifi;
@property BOOL isNightMode;
+ (PicLoadEnableSharedClass*)newInstance;
@end
|
yrq110/HouseRadar | AMapDemo/ListTableViewCell.h | //
// ListTableViewCell.h
// AMapDemo
//
// Created by yrq_mac on 16/1/30.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ListTableViewCell : UITableViewCell
@property(strong,nonatomic)UILabel *titleLabel;
@property(strong,nonatomic)UILabel *cityLabel;
@property(strong,nonatomic)UILabel *priceLabel;
@property(strong,nonatomic)UILabel *publishTimeLabel;
@property(strong,nonatomic)UILabel *roomLabel;
@property(strong,nonatomic)UIButton *clickButton;
@property(strong,nonatomic)UIImageView *houseImageView;
@property(strong,nonatomic)UIScrollView *titleScrollView;
@end |
yrq110/HouseRadar | HouseEntity+CoreDataProperties.h | //
// HouseEntity+CoreDataProperties.h
// AMapDemo
//
// Created by yrq_mac on 16/3/1.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
#import "HouseEntity.h"
NS_ASSUME_NONNULL_BEGIN
@interface HouseEntity (CoreDataProperties)
@property (nullable, nonatomic, retain) NSString *address;
@property (nullable, nonatomic, retain) NSString *broker_name;
@property (nullable, nonatomic, retain) NSString *broker_tel;
@property (nullable, nonatomic, retain) NSString *config;
@property (nullable, nonatomic, retain) NSString *house_description;
@property (nullable, nonatomic, retain) NSString *house_type;
@property (nullable, nonatomic, retain) NSNumber *id;
@property (nullable, nonatomic, retain) id pic_urls;
@property (nullable, nonatomic, retain) NSString *price;
@property (nullable, nonatomic, retain) NSString *publish_time;
@property (nullable, nonatomic, retain) NSString *title_detail;
@property (nullable, nonatomic, retain) NSString *xiaoqu;
@end
NS_ASSUME_NONNULL_END
|
yrq110/HouseRadar | AMapDemo/RadarSearchToolsView.h | //
// RadarSearchToolsView.h
// AMapDemo
//
// Created by yrq_mac on 16/1/31.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RadarSearchToolsView : UIView<UITextFieldDelegate>
@property(strong,nonatomic)UIButton *locationBtn;
@property(strong,nonatomic)UITextField *radiusTF;
@property(strong,nonatomic)UILabel *radiusLabel;
@property(strong,nonatomic)UIButton *searchBtn;
@end
|
yrq110/HouseRadar | AMapDemo/SegmentView.h | <filename>AMapDemo/SegmentView.h
//
// SegmentView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/10.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol SegmentDelegate <NSObject>
- (void)buttonClick:(NSInteger)sender;
- (void)topButtonClick:(NSString*)sender;
@end
@interface SegmentView : UIView
@property(strong,nonatomic)NSMutableArray *segmentArray;
@property(strong,nonatomic)NSArray *array;
@property(strong,nonatomic)id<SegmentDelegate>myDelegate;
-(void)updateSegmentStates:(NSUInteger)index;
-(void)changeColor;
@end
|
yrq110/HouseRadar | HouseEntity.h | //
// HouseEntity.h
// AMapDemo
//
// Created by yrq_mac on 16/3/1.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
NS_ASSUME_NONNULL_BEGIN
@interface HouseEntity : NSManagedObject
// Insert code here to declare functionality of your managed object subclass
@end
NS_ASSUME_NONNULL_END
#import "HouseEntity+CoreDataProperties.h"
|
yrq110/HouseRadar | AMapDemo/FeedBackView.h | //
// FeedBackView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/21.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
@interface FeedBackView : UIView<MFMailComposeViewControllerDelegate>
@property(strong,nonatomic)UILabel *label;
@property(strong,nonatomic)UITextView *textView;
@property(strong,nonatomic)UIButton *button;
@end
|
yrq110/HouseRadar | AMapDemo/ViewController.h | <reponame>yrq110/HouseRadar<filename>AMapDemo/ViewController.h
//
// ViewController.h
// AMapDemo
//
// Created by yrq_mac on 16/1/22.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "AppDelegate.h"
#import "ExactSearchToolsView.h"
#import "RadarSearchToolsView.h"
#import "SegmentView.h"
#import "SettingView.h"
#import "FavoriteView.h"
#import "HistoryView.h"
#import "PinCallOutTappedView.h"
#import "ZFProgressView.h"
#import "QQButton.h"
#import "TopView.h"
#import "ListButtonView.h"
@interface ViewController : UIViewController<UITextFieldDelegate,MAMapViewDelegate,AMapSearchDelegate,CLLocationManagerDelegate,SegmentDelegate,UIAlertViewDelegate>
@property(strong,nonatomic)MAMapView *mapView;
@property(strong,nonatomic)AMapSearchAPI *search;
@property(strong,nonatomic)AMapPOI *MIP;
@property(strong,nonatomic)AMapPOIKeywordsSearchRequest *poiRequest;
@property(strong,nonatomic)CLLocationManager *userLocationManager;
@property(strong,nonatomic)UITextField *cityTextField;
@property(strong,nonatomic)UITextField *searchTextField;
@property(strong,nonatomic)UIButton *searchButton;
@property(strong,nonatomic)UIButton *listButton;
@property(strong,nonatomic)UIButton *radarSearchButton;
@property(strong,nonatomic)UIButton *exactSearchButton;
@property(strong,nonatomic)ExactSearchToolsView *esView;
@property(strong,nonatomic)ListButtonView *listBtnView;
@property int shiListOut;
@property int ListOutNo;
@property(strong,nonatomic)RadarSearchToolsView *rsView;
@property(strong,nonatomic)PinCallOutTappedView *pcotView;
@property(strong,nonatomic)UIView *toolView;
@property(strong,nonatomic)TopView *topView;
//@property(strong,nonatomic)UIView *topView;
@property BOOL isSearch;
+(id)shareViewController;
- (void)searchExcute:(NSString*)keyword city:(NSString*)city title:(NSString*)title price:(NSString*)price brokerName:(NSString*)brokerName brokerTel:(NSString*)brokerTel publishTime:(NSString*)publishTime description:(NSString*)description config:(NSString*)config type:(NSString*)type address:(NSString*)address;
@property(strong,nonatomic)NSArray *longArray;
@property(strong,nonatomic)NSArray *latiArray;
@property(strong,nonatomic)SegmentView *segmentView;
@property(strong,nonatomic)SettingView *settingView;
@property(strong,nonatomic)FavoriteView *favoriteView;
@property(strong,nonatomic)HistoryView *historyView;
@property(strong,nonatomic)ZFProgressView *rsProgress;
@property(strong,nonatomic)QQButton *mapTypeBtn;
@property(strong,nonatomic)QQButton *trafficBtn;
@property(strong,nonatomic)NSTimer *timer;
@end
|
yrq110/HouseRadar | CompareEntity.h | //
// CompareEntity.h
// AMapDemo
//
// Created by yrq_mac on 16/3/1.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
NS_ASSUME_NONNULL_BEGIN
@interface CompareEntity : NSManagedObject
// Insert code here to declare functionality of your managed object subclass
@end
NS_ASSUME_NONNULL_END
#import "CompareEntity+CoreDataProperties.h"
|
yrq110/HouseRadar | AMapDemo/HouseListViewController.h | <reponame>yrq110/HouseRadar
//
// HouseListViewController.h
// AMapDemo
//
// Created by yrq_mac on 16/1/30.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TopView.h"
@interface HouseListViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
+(id)shareHouseListViewController;
@property(strong,nonatomic)UITableView *tableView;
@property(strong,nonatomic)UIRefreshControl *refresh;
@property(strong,nonatomic)UIView *infiniteScrollView;
@property(strong,nonatomic)NSMutableArray *titleArray;
@property(strong,nonatomic)NSMutableArray *addressArray;
@property(strong,nonatomic)NSMutableArray *priceArray;
@property(strong,nonatomic)NSMutableArray *roomArray;
@property(strong,nonatomic)NSMutableArray *picURLArray;
@property(strong,nonatomic)NSMutableArray *configArray;
@property(strong,nonatomic)NSMutableArray *descriptionArray;
@property(strong,nonatomic)NSMutableArray *publishTimeArray;
@property(strong,nonatomic)NSMutableArray *brokerNameArray;
@property(strong,nonatomic)NSMutableArray *brokerTelArray;
@property(strong,nonatomic)NSMutableArray *xiaoquArray;
@property(strong,nonatomic)NSString *outXiaoqu;
@property(strong,nonatomic)NSString *outPrice;
@property(strong,nonatomic)TopView *topView;
//@property(strong,nonatomic)UIView *topView;
//@property(strong,nonatomic)UIButton *returnButton;
//@property(strong,nonatomic)UILabel *topLabel;
@property(strong,nonatomic)UIImageView *loadingImageView;
@property(strong,nonatomic)NSTimer *loadingTimer;
@property(strong,nonatomic)NSTimer *GETTimer;
@end
|
yrq110/HouseRadar | AMapDemo/ExactSearchToolsView.h | <filename>AMapDemo/ExactSearchToolsView.h
//
// ExactSearchToolsView.h
// AMapDemo
//
// Created by yrq_mac on 16/1/31.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ExactSearchToolsView : UIView<UITextFieldDelegate>
@property(strong,nonatomic)UILabel *priceLabel;
@property(strong,nonatomic)UITextField *priceTF;
@property(strong,nonatomic)UILabel *roomLabel;
@property(strong,nonatomic)UITextField *shiTF;
@property(strong,nonatomic)UILabel *shiLabel;
@property(strong,nonatomic)UITextField *tingTF;
@property(strong,nonatomic)UILabel *tingLabel;
@property(strong,nonatomic)UITextField *weiTF;
@property(strong,nonatomic)UILabel *weiLabel;
@property(strong,nonatomic)UIButton *detailButton;
@property(strong,nonatomic)UIButton *shiBtn;
@property(strong,nonatomic)UIButton *tingBtn;
@property(strong,nonatomic)UIButton *weiBtn;
@end
|
yrq110/HouseRadar | AMapDemo/FavoriteView.h | //
// FavoriteView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/10.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TopView.h"
@interface FavoriteView : UIView<UITableViewDataSource,UITableViewDelegate>
@property(strong,nonatomic)NSString *titleString;
@property(strong,nonatomic)UITableView *tableView;
@property(strong,nonatomic)TopView *topView;
//@property(strong,nonatomic)UIView *topView;
//@property(strong,nonatomic)UILabel *topLabel;
@property(strong,nonatomic)NSMutableArray *titleArray;
@property(strong,nonatomic)NSMutableArray *addressArray;
@property(strong,nonatomic)NSMutableArray *priceArray;
@property(strong,nonatomic)NSMutableArray *roomArray;
@property(strong,nonatomic)NSMutableArray *picURLArray;
@property(strong,nonatomic)NSMutableArray *configArray;
@property(strong,nonatomic)NSMutableArray *descriptionArray;
@property(strong,nonatomic)NSMutableArray *publishTimeArray;
@property(strong,nonatomic)NSMutableArray *brokerNameArray;
@property(strong,nonatomic)NSMutableArray *brokerTelArray;
@property(strong,nonatomic)NSMutableArray *xiaoquArray;
- (void)reloadTableViewData:(NSMutableArray*)titleArray address:(NSMutableArray*)addressArray price:(NSMutableArray*)priceArray room:(NSMutableArray*)roomArray priURL:(NSMutableArray*)picURLArray config:(NSMutableArray*)configArray description:(NSMutableArray*)descriptionArray publishTime:(NSMutableArray*)publishTimeArray brokerName:(NSMutableArray*)brokerNameArray brokerTel:(NSMutableArray*)brokerTelArray xiaoqu:(NSMutableArray*)xiaoquArray;
+ (FavoriteView*)sharedFavoriteView;
@end
|
yrq110/HouseRadar | AMapDemo/CompareView.h | //
// CompareView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/29.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CompareView : UIView
@property(strong,nonatomic)UILabel *priceLabel;
@property(strong,nonatomic)UILabel *xiaoquLabel;
@property(strong,nonatomic)UILabel *typeLabel;
@property(strong,nonatomic)UIImageView *houseImageView;
@property(strong,nonatomic)UIScrollView *typeScrollView;
@property(strong,nonatomic)UIScrollView *mainScrollView;
@property(strong,nonatomic)UIButton *deleteBtn;
@end
|
yrq110/HouseRadar | AMapDemo/HouseAnnotationView.h | <reponame>yrq110/HouseRadar
//
// HouseAnnotationView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/6.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <MAMapKit/MAMapKit.h>
#import "HouseCalloutView.h"
@interface HouseAnnotationView : MAPinAnnotationView
@property (nonatomic, readonly) HouseCalloutView *calloutView;
@end
|
yrq110/HouseRadar | AMapDemo/PinCallOutTappedView.h | <reponame>yrq110/HouseRadar
//
// PinCallOutTappedView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/11.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface PinCallOutTappedView : UIView
@property(strong,nonatomic)UIButton *goBtn;
@property(strong,nonatomic)UIButton *detailBtn;
@end
|
yrq110/HouseRadar | AMapDemo/HouseCalloutView.h | //
// HouseCalloutView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/6.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface HouseCalloutView : UIView
@property (nonatomic, strong) UIImage *image; //商户图
@property (nonatomic, copy) NSString *title; //商户名
@property (nonatomic, copy) NSString *subtitle; //地址
@property (nonatomic, strong) UIImageView *portraitView;
@property (nonatomic, strong) UILabel *subtitleLabel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (strong,nonatomic)UIButton *btn;
@end
|
yrq110/HouseRadar | AMapDemo/VersionDetailView.h | //
// VersionDetailView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/21.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TopView.h"
@interface VersionDetailView : UIView
@property(strong,nonatomic)TopView *topView;
@property(strong,nonatomic)UILabel *versionNum;
@property(strong,nonatomic)UILabel *versionTime;
@property(strong,nonatomic)UILabel *introduction;
@property(strong,nonatomic)UILabel *detail;
@end
|
yrq110/HouseRadar | AMapDemo/QQButton.h | //
// QQButton.h
// QQBtn
//
// Created by MacBook on 15/6/25.
// Copyright (c) 2015年 维尼的小熊. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface QQButton : UIButton
/** 大圆脱离小圆的最大距离 */
@property (nonatomic, assign) CGFloat maxDistance;
/** 小圆 */
@property (nonatomic, strong) UIView *samllCircleView;
@end
|
yrq110/HouseRadar | AMapDemo/StaffView.h | <gh_stars>1-10
//
// StaffView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/29.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TopView.h"
@interface StaffView : UIView
@property(strong,nonatomic)TopView *topView;
@end
|
yrq110/HouseRadar | AMapDemo/ListButtonView.h | //
// ListButtonView.h
// AMapDemo
//
// Created by yrq_mac on 16/3/2.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ListButtonView : UIView
@property(strong,nonatomic)UIScrollView *scrollView;
@end
|
yrq110/HouseRadar | AMapDemo/HouseDetailView.h | <filename>AMapDemo/HouseDetailView.h
//
// HouseDetailView.h
// AMapDemo
//
// Created by yrq_mac on 16/1/31.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TopView.h"
@interface HouseDetailView : UIView<UIScrollViewDelegate>
//0-list 1-mainMap 2-collect
@property int typeInt;
@property(strong,nonatomic)UIButton *goToMapBtn;
@property(strong,nonatomic)UIButton *collectBtn;
@property(strong,nonatomic)UIButton *deleteBtn;
@property(strong,nonatomic)UILabel *titleLabel;
@property(strong,nonatomic)UILabel *priceLabel;
@property(strong,nonatomic)UILabel *brokerNameLabel;
@property(strong,nonatomic)UILabel *brokerTelLabel;
@property(strong,nonatomic)UILabel *publishTimeLabel;
@property(strong,nonatomic)UILabel *descriptionLabel;
@property(strong,nonatomic)UILabel *configLabel;
@property(strong,nonatomic)UILabel *typeLabel;
@property(strong,nonatomic)UILabel *addressLabel;
@property id imageURL;
@property(strong,nonatomic)UIScrollView *imageScrollView;
@property(strong,nonatomic)UIImageView *houseImageView;
@property(strong,nonatomic)TopView *topView;
@property(strong,nonatomic)UIScrollView *scrollView;
@property(strong,nonatomic)UILabel *price;
@property(strong,nonatomic)UILabel *type;
@property(strong,nonatomic)UILabel *config;
@property(strong,nonatomic)UILabel *house_description;
@property(strong,nonatomic)UILabel *address;
@property(strong,nonatomic)UILabel *publishTime;
@property(strong,nonatomic)UILabel *brokerName;
@property(strong,nonatomic)UILabel *brokerTel;
@property(strong,nonatomic)NSString *xiaoqu;
@property(strong,nonatomic)UIButton *addCompareBtn;
-(void)transTitle:(NSString*)title price:(NSString*)price type:(NSString*)type config:(NSString*)config description:(NSString*)description address:(NSString*)address publishTime:(NSString*)publishTime imageURL:(id)imageURL broker_name:(NSString*)broker_name broker_tel:(NSString*)broker_tel xiaoqu:(NSString*)xiaoqu;
@end
|
yrq110/HouseRadar | AMapDemo/SettingView.h | //
// SettingView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/10.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TopView.h"
#import "SegmentView.h"
#import <MessageUI/MFMailComposeViewController.h>
@interface SettingView : UIView<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,MFMailComposeViewControllerDelegate,SegmentDelegate>
@property(strong,nonatomic)TopView *topView;
//@property(strong,nonatomic)UIView *topView;
//@property(strong,nonatomic)UILabel *topLabel;
@property(strong,nonatomic)UILabel *PicLoadLabel;
@property(strong,nonatomic)UISwitch *PicLoadSwitch;
@property(strong,nonatomic)UILabel *netLoadLabel;
@property(strong,nonatomic)UISwitch *netLoadSwitch;
@property(strong,nonatomic)UILabel *clearFavoriteLabel;
@property(strong,nonatomic)UIButton *clearFavoriteBtn;
@property(strong,nonatomic)UILabel *nightModeLabel;
@property(strong,nonatomic)UISwitch *nightModeSwitch;
@property(strong,nonatomic)UILabel *feedbackLabel;
@property(strong,nonatomic)UIButton *feedbackBtn;
@property(strong,nonatomic)UILabel *versionLabel;
@property(strong,nonatomic)UILabel *versionNo;
@property(strong,nonatomic)UILabel *appDetailLabel;
@property(strong,nonatomic)UIButton *appDetailBtn;
@property(strong,nonatomic)UILabel *staffLabel;
@property(strong,nonatomic)UIButton *staffBtn;
@property(strong,nonatomic)UITableView *tableView;
@end
|
yrq110/HouseRadar | AMapDemo/ContactView.h | //
// ContactView.h
// AMapDemo
//
// Created by yrq_mac on 16/2/23.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TopView.h"
@interface ContactView : UIView
@property(strong,nonatomic)TopView *topView;
@property(strong,nonatomic)UILabel *email;
@property(strong,nonatomic)UILabel *emailDetail;
@property(strong,nonatomic)UILabel *qq;
@property(strong,nonatomic)UILabel *qqDetail;
@property(strong,nonatomic)UILabel *weibo;
@property(strong,nonatomic)UILabel *weiboDetail;
@end
|
yrq110/HouseRadar | CompareEntity+CoreDataProperties.h | //
// CompareEntity+CoreDataProperties.h
// AMapDemo
//
// Created by yrq_mac on 16/3/1.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
#import "CompareEntity.h"
NS_ASSUME_NONNULL_BEGIN
@interface CompareEntity (CoreDataProperties)
@property (nullable, nonatomic, retain) NSString *house_type;
@property (nullable, nonatomic, retain) NSString *pic_url;
@property (nullable, nonatomic, retain) NSString *price;
@property (nullable, nonatomic, retain) NSString *xiaoqu;
@end
NS_ASSUME_NONNULL_END
|
yrq110/HouseRadar | AMapDemo/TipViewController.h | <gh_stars>1-10
//
// TipViewController.h
// AMapDemo
//
// Created by yrq_mac on 16/2/24.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TipViewController : UIViewController<UIScrollViewDelegate>
@property(strong,nonatomic)UIButton *enterBtn;
@end
|