repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
P8P-7/core
|
src/modules/led-strip-controller/include/goliath/led-strip-controller/led_strip_controller.h
|
<reponame>P8P-7/core
#pragma once
#include <goliath/i2c.h>
#include <cstdint>
#include <vector>
namespace goliath::led_controller {
using LedId = std::uint8_t;
using Hue = std::uint8_t;
using Saturation = std::uint8_t;
using Value = std::uint8_t;
using Place = std::uint8_t;
enum class LightingType : std::uint8_t {
SPECIFIC = 0,
ALL = 1,
CIRCLE = 2,
};
enum class ColorType : std::uint8_t {
HSV = 0,
RAINBOW = 1,
};
struct LedStatus {
LightingType lightingType;
ColorType colorType;
Place place;
};
struct SpecificColour {
LedId ledId;
Hue hue;
Saturation saturation;
Value value;
};
struct AllLeds {
Hue hue;
Saturation saturation;
Value value;
bool rainbow;
};
struct SpecificRainbow {
LedId ledId;
Hue startHue;
};
struct Circle {
LedId startId;
LedId endId;
bool cw;
Hue hue;
Saturation saturation;
};
struct SpecColMessage {
LedStatus ledStatus;
SpecificColour specificColour;
};
struct AllLedsMessage {
LedStatus ledStatus;
AllLeds allLeds;
};
struct SpecRainMessage {
LedStatus ledStatus;
SpecificRainbow specificRainbow;
};
struct CircleMessage {
LedStatus ledStatus;
Circle circle;
};
class LedStripController {
public:
explicit LedStripController(i2c::I2cSlave &slave);
/**
* Sends the @param message to the physical controller to process.
* @param message new led status to process
*/
void sendCommand(const SpecColMessage &message);
void sendCommand(const AllLedsMessage &message);
void sendCommand(const SpecRainMessage &message);
void sendCommand(const CircleMessage &message);
const static size_t numberOfPixels = 30;
private:
i2c::I2cSlave &slave;
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/repositories/log_repository.h
|
#pragma once
#include <goliath/foundation.h>
#include <boost/log/trivial.hpp>
#include <boost/log/core.hpp>
#include <boost/log/sinks.hpp>
#include <repositories/LogRepository.pb.h>
#include <thread>
namespace goliath::repositories {
class LogRepository : public Repository {
public:
explicit LogRepository(const size_t &bufferSize);
~LogRepository();
std::unique_ptr<::google::protobuf::Message> getMessage() override;
private:
using SinkType = boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend>;
struct LogEntry {
const std::uint64_t timestamp;
const std::string thread_id;
const boost::log::trivial::severity_level severity;
const std::string message;
};
std::mutex mutex;
size_t bufferSize;
std::deque<LogEntry> history;
boost::shared_ptr<SinkType> sink;
void addEntry(const LogEntry &entry);
void formatter(const boost::log::record_view &record, boost::log::formatting_ostream &stream);
};
}
|
P8P-7/core
|
src/modules/servo/include/goliath/servo/servo_handle.h
|
#pragma once
#include <goliath/foundation.h>
#include "dynamixel/Dynamixel.h"
/**
* @file servo_handle.h
* @author Group 7 - Informatica
*/
namespace goliath::handles {
/**
* @class goliath::handles::servo_handle
* @brief Handle that locks servos
*/
class ServoHandle : public Handle {
public:
/**
* @param device The dynamixel device.
*/
ServoHandle(const size_t &id, std::shared_ptr<dynamixel::Dynamixel> device);
/**
* @return Currently set device
*/
std::shared_ptr<dynamixel::Dynamixel> getDevice();
private:
std::shared_ptr<dynamixel::Dynamixel> device;
};
}
|
P8P-7/core
|
src/modules/openal/include/goliath/openal/device.h
|
<reponame>P8P-7/core
#pragma once
#include <iostream>
#include <AL/al.h>
#include <AL/alc.h>
/**
* @file device.h
* @author Group 7 - Informatica
*/
namespace goliath::openal {
/**
* @class goliath::openal::Device
* @brief Base class for any audio device
*/
class Device {
public:
/**
* @param deviceName Location of device (Default NULL)
*/
explicit Device(ALchar *deviceName = nullptr);
virtual ~Device();
ALCdevice* getDevice() const;
protected:
ALCdevice *alcDevice;
};
}
|
P8P-7/core
|
src/modules/vision/include/goliath/vision/util/vision_utilities.h
|
#pragma once
/**
* @file vision_utilities.h
* @author Group 7 - Informatica
*/
namespace goliath::util {
/**
* @class goliath::util::VisionUtilities
* @brief Contains useful utility function for vision calculations
*/
class VisionUtilities {
public:
/**
* @brief Maps a numeric value in a range to a the same position in another range
* @tparam T Numeric value
* @param input Input value
* @param inputMin Input range lower bound
* @param inputMax Input range upper bound
* @param outputMin Output range lower bound
* @param outputMax Output range upper bound
* @return Numeric value mapped to new range
*/
template<typename T>
static T map(T input, T inputMin, T inputMax, T outputMin, T outputMax) {
return (input - inputMin) * (outputMax - outputMin) / (inputMax - inputMin) + outputMin;
}
template<typename T>
static T map(T input, T inputMax, T outputMax) {
return map(input, static_cast<T>(0), inputMax, static_cast<T>(0), outputMax);
}
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/commands/queue_command.h
|
#pragma once
#include <thread>
#include "command.h"
namespace goliath::commands {
/**
* @class goliath::commands::QueueCommand executes the incoming command in a worker thread.
*/
class QueueCommand : public Command {
public:
QueueCommand(const size_t &id, const std::vector<size_t> &requiredHandles);
~QueueCommand();
void run(handles::HandleMap &handles, const proto::CommandMessage &message) override;
/**
* @brief always true because a QueueCommand can receive command in parallel
* @return true
*/
bool canRunParallel() const override;
void interrupt() override;
protected:
/**
* @brief mutex protecting the queue
*/
std::mutex queueMutex;
std::condition_variable cv;
handles::HandleMap handles;
std::queue<proto::CommandMessage> queue;
/**
* Should be overriden by a child. Processes items in the queue.
*/
virtual void process() = 0;
private:
void work();
bool isWorking;
std::thread worker;
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/commands/move_arm_command.h
|
#pragma once
#include <goliath/servo.h>
#include "basic_command.h"
#include "../handles.h"
namespace goliath::commands {
class MoveArmCommand : public BasicCommand {
public:
explicit MoveArmCommand(const size_t &id);
private:
void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override;
};
}
|
P8P-7/core
|
src/modules/transitions/include/goliath/transitions/util/transition_utilities.h
|
#pragma once
/**
* @file transition_utilities.h
* @author Group 7 - Informatica
*/
namespace goliath::util {
/**
* @class goliath::util::TransitionUtilities
* @brief Contains utilities for transitions
*/
class TransitionUtilities {
public:
template<typename T>
static T map(T input, T inputMin, T inputMax, T outputMin, T outputMax) {
return (input - inputMin) * (outputMax - outputMin) / (inputMax - inputMin) + outputMin;
}
template<typename T>
static T map(T input, T inputMax, T outputMax) {
return map(input, static_cast<T>(0), inputMax, static_cast<T>(0), outputMax);
}
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/commands/shutdown_command.h
|
<reponame>P8P-7/core<filename>src/controller/include/goliath/controller/commands/shutdown_command.h
#pragma once
#include "../watcher.h"
#include <goliath/zmq-messaging.h>
#include <boost/asio/io_service.hpp>
#include "basic_command.h"
/**
* @file shutdown_command.h
* @author Group 7 - Informatica
*/
namespace goliath::commands {
class ShutdownCommand : public BasicCommand {
public:
ShutdownCommand(const size_t &id, std::shared_ptr<boost::asio::io_service> ioService);
private:
std::shared_ptr<boost::asio::io_service> ioService;
void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override;
};
}
|
P8P-7/core
|
src/modules/vision/include/goliath/vision/webcam.h
|
#pragma once
#include <opencv2/opencv.hpp>
#include <boost/optional.hpp>
#include <goliath/vision/processors/roi_processor.h>
/**
* @file webcam.h
* @author Group 7 - Informatica
*/
namespace goliath::vision {
/**
* @class goliath::vision::Webcam
* @brief Wrapper class around VideoCapture
*/
class Webcam {
public:
/**
* @param capId VideoCapture to be used
*/
explicit Webcam(int capId);
/**
* @param capId VideoCapture to be used
* @param color Convert incoming image to a specific format, must always start with CV_BGR2<color>
*/
Webcam(int capId, int color);
~Webcam();
/**
* @brief Capture a frame and assign it to argument
* @param frame Frame to be assigned with captured frame
*/
void getFrame(cv::Mat& frame);
/**
* @return Captured frame
*/
cv::Mat getFrame();
void getRoiFrame(cv::Mat &frame, const vision::RoiProcessor& roiProcessor);
cv::Mat getRoiFrame(const vision::RoiProcessor& roiProcessor);
private:
const int capId;
cv::VideoCapture cap;
/**
* @brief Unset if not converted to specific color, else set to a CV_BGR2<color>
*/
boost::optional<const int> color;
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/command_executor.h
|
<gh_stars>1-10
#pragma once
#include <boost/asio.hpp>
#include "command_map.h"
#include "handle_map.h"
/**
* @file command_executor.h
* @author Group 7 - Informatica
*/
using namespace goliath::handles;
namespace goliath::commands {
/**
* @class goliath::commands::CommandExecutor
* @brief Takes in a command id, and executes is. Also checks handles and interrupts commands
*/
class CommandExecutor {
public:
/**
* @param commands Command Map
* @param handles Handle Map
*/
CommandExecutor(size_t numberOfThreads, CommandMap &commands, HandleMap &handles);
~CommandExecutor();
/**
* @brief Checks if a command is already running, if so drop it else execute it's instance by running
* @see tryExecute. Sets status of command to running.
* @param commandId ID of the command to run
* @param message Arguments gathered from the protobuf input
*/
void run(size_t commandId, const proto::CommandMessage &message);
void run(size_t commandId);
private:
const size_t numberOfThreads;
size_t numberOfActiveCommands;
CommandMap &commands;
HandleMap &handles;
boost::asio::thread_pool pool;
std::mutex mutex;
/**
* Running on it's own thread. Checks if the handles the command requires are occupied. If so, call
* interrupt() on all command's currently using the handles the new command requires. After that waits for
* the condition variable to be triggered to then check again. If all handles are free, execute the command
* in the current thread. Sets status to started.
* @param commandId ID of the command to try to execute
* @param message Arguments gathered from the protobuf input
*/
void start(const size_t &commandId, const proto::CommandMessage &message);
void delayedStart(const size_t &commandId, const proto::CommandMessage &message);
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/command_map.h
|
#pragma once
#include "command_item.h"
#include "commands/command.h"
#include "repositories/command_status_repository.h"
/**
* @file command_map.h
* @author Group 7 - Informatica
*/
namespace goliath::commands {
/**
* @class goliath::commands::CommandMap
* @brief Wrapper around a map storing indexes (Command ID's) and @see goliath::commands::CommandItem
*/
class CommandMap {
public:
using iterator = std::map<size_t, CommandItem>::iterator;
using const_iterator = std::map<size_t, CommandItem>::const_iterator;
explicit CommandMap(std::shared_ptr<repositories::CommandStatusRepository> statusRepository);
/**
* @param commands Initial map
*/
CommandMap(std::shared_ptr<repositories::CommandStatusRepository> statusRepository, std::map<size_t, CommandItem> commands);
/**
* @brief Add a goliath::commands::CommandItem to the map
* @param command Pointer to @see goliath::commands::Command instance
*/
CommandItem &add(std::shared_ptr<Command> command);
/**
* @brief Add a goliath::commands::CommandItem to the map.
* Creates an instance of CommandType with handleId and args passed to it as arguments. CommandType's
* constructor should accept an commandId as its first argument.
* @tparam CommandType type to create an Command of
* @tparam Targs types of arguments passed to
* @param commandId passed to the command created
* @param args arguments passed the command in the constructor after the commandId
* @return goliath::commands::CommandItem with
*/
template<typename CommandType, typename ...Targs>
CommandItem &add(size_t commandId, Targs... args);
/**
* @brief Get goliath::commands::CommandItem at id
* @param id ID
* @return @see goliath::commands::CommandItem
*/
CommandItem &operator[](size_t id);
const CommandItem &operator[](size_t id) const;
/**
* @brief Check if a goliath::commands::Command exists
* @param id ID to check
* @return Status
*/
bool commandExists(size_t id) const;
std::shared_ptr<repositories::CommandStatusRepository> &getStatusRepository();
/**
* @brief Begin iterator
* @return Map iterator
*/
iterator begin();
/**
* @brief End iterator
* @return Map iterator
*/
iterator end();
/**
* @brief Begin iterator
* @return Constant map iterator
*/
const_iterator begin() const;
/**
* @brief End iterator
* @return Constant map iterator
*/
const_iterator end() const;
private:
std::shared_ptr<repositories::CommandStatusRepository> statusRepository;
std::map<size_t, CommandItem> map;
};
template<typename CommandType, typename ...Targs>
CommandItem &CommandMap::add(size_t commandId, Targs... args) {
auto command = std::make_shared<CommandType>(commandId, args...);
return add(command);
}
}
|
P8P-7/core
|
src/modules/vision/include/goliath/vision/processors/canny_processor.h
|
<reponame>P8P-7/core<filename>src/modules/vision/include/goliath/vision/processors/canny_processor.h
#pragma once
#include "processor.h"
/**
* @file canny_processor.h
* @author Group 7 - Informatica
*/
namespace goliath::vision {
/**
* @brief Default kernel size
*/
const int DEFAULT_CANNY_KERNEL = 3;
/**
* @class goliath::vision::CannyProcessor
* @brief Processor that returns a canny image of the input
*/
class CannyProcessor : public Processor {
public:
/**
* @param input Source image
* @param minLowThreshold Canny min threshold
* @param maxLowThreshold Canny max threshold
*/
explicit CannyProcessor(const cv::Mat &input, int minLowThreshold, int maxLowThreshold);
explicit CannyProcessor(Processor &other, int minLowThreshold, int maxLowThreshold);
/**
* @return Canny image
*/
cv::Mat process() const override;
private:
int minLowThreshold, maxLowThreshold;
};
}
|
P8P-7/core
|
src/modules/i2c/include/goliath/i2c/handles/i2c_bus_handle.h
|
#pragma once
#include <string>
#include <goliath/foundation.h>
/**
* @file i2c_bus_handle.h
* @author Group 7 - Informatica
*/
namespace goliath::handles {
class I2cBusHandle : public Handle {
public:
I2cBusHandle(const size_t &id, const std::string &device);
/**
* @return path to i2c device
*/
const std::string& getDevicePath() const;
private:
std::string device;
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/commands/dance_command.h
|
#pragma once
#include <goliath/servo/wings/wing_command.h>
#include <goliath/servo/wings/wing_controller.h>
#include <goliath/servo/repositories/wing_state_repository.h>
#include <goliath/motor-controller.h>
#include "../handles.h"
#include "basic_command.h"
/**
* @file dance_command.h
* @author Group 7 - Informatica
*/
namespace goliath::commands {
class DanceCommand : public BasicCommand {
public:
DanceCommand(const size_t &id, const std::shared_ptr<repositories::WingStateRepository> &repository,
const std::uint8_t chainSawSpeedLow, const std::uint8_t chainSawSpeedMedium,
const std::uint8_t chainSawSpeedFast, const std::uint8_t chainSawSpeedExtraFast);
private:
std::shared_ptr<repositories::WingStateRepository> repository;
const std::uint8_t chainSawSpeedLow;
const std::uint8_t chainSawSpeedMedium;
const std::uint8_t chainSawSpeedFast;
const std::uint8_t chainSawSpeedExtraFast;
void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override;
void saw(motor_controller::MotorController &motorController, motor_controller::MotorId motor, std::uint8_t speed);
void moveWingOverTime(const std::chrono::milliseconds &duration, servo::WingController &wingController,
std::vector<servo::WingCommand> commands);
motor_controller::MotorId motorHandleToId(handles::HandleMap &handles, size_t handle);
void stand(handles::HandleMap &handles);
};
}
|
P8P-7/core
|
src/modules/transitions/include/goliath/transitions/methods/eases.h
|
#pragma once
/**
* @file eases.h
* @author Group 7 - Informatica
*/
/**
* @namespace goliath::transitions::methods
* @brief Contains methods for transitioning a phase
*/
namespace goliath::transitions::methods {
double easeInQuad(double value);
double easeOutQuad(double value);
double easeInOutQuad(double value);
double easeInCubic(double value);
double easeOutCubic(double value);
double easeInOutCubic(double value);
double easeInQuart(double value);
double easeOutQuart(double value);
double easeInOutQuart(double value);
double easeInQuint(double value);
double easeOutQuint(double value);
double easeInOutQuint(double value);
double linear(double value);
}
|
P8P-7/core
|
src/modules/servo/src/wings/wings/deadzone_transition.h
|
<gh_stars>1-10
#pragma once
#include <goliath/servo.h>
namespace goliath::servo {
class DeadzoneTransitionController {
public:
DeadzoneTransitionController(
WingController *controller,
handles::WingHandle &handle,
Direction direction,
std::uint16_t speed);
DeadzoneTransitionController(
WingController *controller,
servo::WingCommand command);
void prestart();
bool canStart();
void start();
bool tick();
void stop();
bool isInDeadzone() const;
bool isStarted() const;
private:
const static int threshold = 256;
const static std::size_t historySize = 1;
const static std::size_t bufferSize = historySize * 4;
const static int margin = 25;
std::deque<int> history;
bool started;
WingController *controller;
handles::WingHandle &handle;
Direction direction;
std::uint16_t speed;
const servo::WingState &state;
int getTargetPosition() const;
int getThreshold() const;
bool isInThreshold(int value) const;
int getBoundaryPosition() const;
};
}
|
P8P-7/core
|
src/controller/include/goliath/controller/commands/basic_command.h
|
<gh_stars>1-10
#pragma once
#include "command.h"
namespace goliath::commands {
class BasicCommand : public Command {
public:
BasicCommand(const size_t &id, const std::vector<size_t> &requiredHandles);
void run(handles::HandleMap &handles, const proto::CommandMessage &message) override;
protected:
/**
* @brief The actual execute method implemented by underlying commands
* @param handles Handle map to be passed to implementation to be unlocked dynamically
* @param message Arguments to be passed to implementers
*/
virtual void execute(handles::HandleMap &handles, const proto::CommandMessage &message) = 0;
};
}
|
kippler/HostsToggler
|
resource.h
|
<reponame>kippler/HostsToggler
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by resource.rc
//
#define IDC_MYICON 2
#define IDD_HBITMAPSAMPLE_DIALOG 102
#define IDM_ABOUT 104
#define IDI_HBITMAPSAMPLE 107
#define IDI_SMALL 108
#define IDC_HBITMAPSAMPLE 109
#define IDC_ACCEL 109
#define IDR_MAINFRAME 128
#define IDI_ICON0 130
#define IDI_ICON1 133
#define IDI_ICON2 134
#define IDR_MENU_TRAY 135
#define IDI_ICON3 136
#define ID_TRAYMENU_IDM 32772
#define IDM_EXIT 32773
#define ID_TRAYMENU_32774 32774
#define IDM_OPEN_FOLDER 32775
#define ID_TRAYMENU_HOSTS 32776
#define IDM_HOSTS_1 32777
#define ID_TRAYMENU_HOSTS32778 32778
#define IDM_HOSTS_2 32779
#define ID_TRAYMENU_NOTEPADHOSTS 32780
#define ID_TRAYMENU_NOTEPADHOSTS32781 32781
#define IDM_NOTEPAD_HOSTS_1 32782
#define IDM_NOTEPAD_HOSTS_2 32783
#define ID_TRAYMENU_NOTEPADHOSTS32784 32784
#define IDM_NOTEPAD_HOSTS_0 32785
#define ID_TRAYMENU_32786 32786
#define IDM_NOTEPAD_HOSTS_3 32787
#define IDM_HOSTS_0 32788
#define IDM_HOSTS_3 32789
#define IDM_NOTEPAD_HOSTS 32790
#define IDC_STATIC -1
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 137
#define _APS_NEXT_COMMAND_VALUE 32791
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 110
#endif
#endif
|
kippler/HostsToggler
|
Global.h
|
#pragma once
extern UINT WM_TASKBARCREATED;
extern UINT WM_TRAY_NOTIFY;
BOOL Tray_NotifyDelete(HWND hWnd, UINT uID);
BOOL Tray_NotifyAdd(HWND hWnd, UINT uID, HICON hIcon, LPCTSTR lpszTip);
BOOL Tray_NotifyModify(HWND hWnd, UINT uID, HICON hIcon, LPCTSTR lpszTip);
BOOL IsFile(LPCTSTR szPathName);
BOOL GetFileCRC(LPCTSTR szFileName, DWORD &dwResult,int nStartPos=0);
|
kippler/HostsToggler
|
stdafx.h
|
<reponame>kippler/HostsToggler<gh_stars>1-10
#pragma once
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <commdlg.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
// ATL SUPPORT
#include <atlbase.h>
extern CComModule _Module;
#include <atlcom.h>
#include <atlwin.h>
#include <atltypes.h>
#include <atlcoll.h>
#include <atlstr.h>
#include <atltime.h>
#define ASSERT(x) ATLASSERT(x)
// manifest
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='<KEY>' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='<KEY>' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='<KEY>' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='<KEY>' language='*'\"")
#endif
#endif
|
Cydox/DesignAndConstruction
|
main.c
|
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define PI 3.141592653589
#define PANEL_WIDTH 400
#define PANEL_LENGTH 500
#define C 4
#define RIVET_C 2.1
#define RIVET_SAFETY 0.8
#define BUCKLING_REQUIREMENT 15000
#define FAILURE_REQUIREMENT 30000
typedef struct material{
char* name;
double E;
double rho;
double sigmaYield;
double sigmaUlt;
} material;
typedef struct element {
double x;
double y;
double y_pos;
bool notFailed;
} element;
double elementArea(const element* e) {
if (!e->notFailed) {
return 0;
} else {
return e->x * e->y;
}
}
double elementY(const element* e) {
return e->y_pos + (e->y / 2);
}
double elementQ(const element* e) {
if (!e->notFailed) {
return 0;
} else {
return elementArea(e) * elementY(e);
}
}
double elementIx(const element* e) {
if (!e->notFailed) {
return 0;
} else {
return (1.0 / 12.0) * (e->x * e->y * e->y * e->y);
}
}
typedef struct stringer {
double y_pos;
element e1;
element e2;
bool notFailed;
} stringer;
stringer newStringer(double y, double w, double t) {
stringer s = {y, {w, t, y, true}, {t, w - t, y + t, true}, true};
return s;
}
double stringerArea(const stringer* s) {
if (!s->notFailed) {
return 0;
} else {
return elementArea(&(s->e1)) + elementArea(&(s->e2));
}
}
double stringerQ(const stringer* s) {
if (!s->notFailed) {
return 0;
} else {
return elementQ(&(s->e1)) + elementQ(&(s->e2));
}
}
double stringerY(const stringer* s) {
if (!s->notFailed) {
return 0;
} else {
return stringerQ(s) / stringerArea(s);
}
}
double stringerIx(const stringer* s) {
if (!s->notFailed) {
return 0;
} else {
return elementIx(&(s->e1)) + elementArea(&(s->e1)) * (elementY(&(s->e1)) - stringerY(s)) * (elementY(&(s->e1)) - stringerY(s)) + elementIx(&(s->e2)) + elementArea(&(s->e2)) * (elementY(&(s->e2)) - stringerY(s)) * (elementY(&(s->e2)) - stringerY(s))/* + stringerArea(s) * stringerY(s) * stringerY(s)*/;
}
}
typedef struct panel {
element sheet;
stringer stringer;
material m;
int numberOfStringers;
} panel;
panel newPanel(int n, double sheetThickness, double stringerWidth, double stringerThickness, material m) {
stringer stringer = newStringer(sheetThickness, stringerWidth, stringerThickness);
element sheet = {PANEL_WIDTH, sheetThickness, 0, 1};
panel p = {sheet, stringer, m, n};
return p;
}
double panelArea(const panel* p) {
return elementArea(&(p->sheet)) + p->numberOfStringers * stringerArea(&(p->stringer));
}
double panelQ(const panel* p) {
return elementQ(&(p->sheet)) + p->numberOfStringers * stringerQ(&(p->stringer));
}
double panelY(const panel* p) {
return panelQ(p) / panelArea(p);
}
double panelIx(const panel* p) {
return elementIx(&(p->sheet)) + elementArea(&(p->sheet)) * (elementY(&(p->sheet)) - panelY(p)) * (elementY(&(p->sheet)) - panelY(p)) + p->numberOfStringers * (stringerIx(&(p->stringer)) + stringerArea(&(p->stringer)) * (stringerY(&(p->stringer)) - panelY(p)) * (stringerY(&(p->stringer)) - panelY(p)));
}
double panelYield(const panel* p) {
return panelArea(p) * p->m.sigmaYield;
}
double panelUltFailure(const panel* p) {
return panelArea(p) * p->m.sigmaUlt;
}
double panelSheetBuckling(const panel* p) {
if (!p->sheet.notFailed) {
return -1;
} else {
double Kc[] = {3.6,3.6,5.12,4,3.6,3.65,3.6,3.6,3.6,3.6};
double pitch = PANEL_WIDTH / (p->numberOfStringers - 1.0);
return panelArea(p) * Kc[p->numberOfStringers] * p->m.E * (p->sheet.y / pitch) * (p->sheet.y / pitch);
}
}
double panelColumnBuckling(const panel* p) {
if (!p->stringer.notFailed) {
return -1;
} else {
return (C * PI * PI * p->m.E * panelIx(p)) / (PANEL_LENGTH * PANEL_LENGTH);
}
}
int getIndexOfMinFail(double failures[3]) {
int index = 0;
double val = failures[0];
for (int i = 1; i < 3; i++) {
if (failures[i] < val && failures[i] != -1) {
val = failures[i];
index = i;
}
}
return index;
}
double calcRivetSpace(const panel* p) {
return RIVET_SAFETY * sqrt((0.9 * RIVET_C * p->m.E * p->sheet.y * p->sheet.y) / (BUCKLING_REQUIREMENT / panelArea(p)));
}
int numberOfRivets(const panel* p) {
double s = calcRivetSpace(p);
return (int) ((PANEL_LENGTH - (2 * 30)) / s) * p->numberOfStringers;
}
double interRivetBuckling(const panel* p) {
if (!p->sheet.notFailed) {
return -1;
} else {
double s = calcRivetSpace(p);
return 0.9 * RIVET_C * p->m.E * (p->sheet.y / s) * (p->sheet.y / s) * panelArea(p);
}
}
double panelMass(const panel* p) {
return (PANEL_LENGTH * panelArea(p) * p->m.rho / 1000) + ((numberOfRivets(p) * 0.488) - (p->m.rho * PI * 1.5 * 1.5 * (p->sheet.y + p->stringer.e2.x) / 1000));
}
void progressiveFailureAnalysis(panel* p, double* buckling, double* failure) {
bool failed = false;
bool buckled = false;
while (!failed) {
double failures[] = {panelUltFailure(p), panelSheetBuckling(p), panelColumnBuckling(p), interRivetBuckling(p)};
int index = getIndexOfMinFail(failures);
if (index == 0) {
failed = true;
*failure = failures[0];
printf(",all,%f", *failure);
} else if (index == 1 && !buckled) {
buckled = true;
*buckling = failures[1];
p->sheet.notFailed = false;
printf(",sheet,%f", *buckling);
} else if (index == 1 && buckled) {
failed = true;
*failure = failures[1];
printf(",sheet,%f", *failure);
} else if (index == 2 && !buckled) {
buckled = true;
*buckling = failures[2];
p->stringer.notFailed = false;
printf(",stringers,%f", *buckling);
} else if (index == 2 && buckled) {
failed = true;
*failure = failures[2];
printf(",stringers,%f", *failure);
} else if (index == 3 && !buckled) {
buckled = true;
p->sheet.notFailed = false;
*buckling = failures[3];
printf(",interrivet,%f", *buckling);
} else if (index == 3 && buckled) {
failed = true;
*failure = failures[3];
printf(",interrivet,%f", *failure);
}
}
printf("\n");
}
void optimizationAnalysis(material m, double sheetThickness, double stringerDimension[2]) {
int numberOfStringers = 0;
double failure = 0;
double buckling = 0;
for (int i = 2; (failure < FAILURE_REQUIREMENT) || (buckling < BUCKLING_REQUIREMENT); i++) {
panel p = newPanel(i, sheetThickness, stringerDimension[0], stringerDimension[1], m);
printf("%s,%f,%f,%f,%f,%f,%d", m.name, panelMass(&p), sheetThickness, stringerDimension[0], stringerDimension[1], calcRivetSpace(&p), i);
progressiveFailureAnalysis(&p, &buckling, &failure);
}
}
int main() {
/*//element e = {0.1, 0.1, 0.0, .constant = 1};
stringer s = newStringer(0.0, 20.0, 1.5);
material al = {72400,0,345,483};
panel p = newPanel(5, 0.8, 20.0, 1.5, al);
printf("%f\n", panelIx(&p));
printf("%f\n", panelSheetBuckling(&p));
printf("%f\n", panelColumnBuckling(&p));
printf("%f\n", panelYield(&p));
printf("%f\n", panelUltFailure(&p));
//printf("%f\n", elementArea(&e));
//printf("%f\n", elementY(&e));
//printf("%f\n", elementQ(&e));
//printf("%f\n", elementIx(&e));*/
material aluminum = {"Aluminum", 72400, 2.78, 345, 483};
material steel = {"Steel", 210000, 7.8, 1100, 1275};
double sheetThicknesses[] = {0.8, 1.0, 1.2};
double aluminumStringerDimensions[][2] = {{20, 1.5}, {20, 2}, {15, 1}, {15, 1.5}};
double steelStringerDimensions[][2] = {{15, 1.5}, {15, 2}};
double buckling = 0;
double failure = 0;
panel original = newPanel(7, 0.8, 20, 1.5, aluminum);
printf("%s,%f,%f,%f,%f,%f,%d", aluminum.name, panelMass(&original), 0.8, 20.0, 1.5, calcRivetSpace(&original), 7);
progressiveFailureAnalysis(&original, &buckling, &failure);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
optimizationAnalysis(aluminum, sheetThicknesses[i], aluminumStringerDimensions[j]);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
optimizationAnalysis(steel, sheetThicknesses[i], steelStringerDimensions[j]);
}
}
return 0;
}
|
Praj41/MergeSort_threads
|
Timer.h
|
#pragma once
#include <iostream>
#include <chrono>
class Timer {
std::chrono::time_point< std::chrono::high_resolution_clock> StartTimePoint;
unsigned int _step;
public:
Timer() : _step(0) {
StartTimePoint = std::chrono::high_resolution_clock::now();
}
~Timer() {
auto EndTimePoint = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<std::chrono::microseconds>(StartTimePoint).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::microseconds>(EndTimePoint).time_since_epoch().count();
auto duration = end - start;
std::cout << duration << "us (" << duration * 0.001 << "ms) - END" << std::endl;
}
void lap() {
auto EndTimePoint = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<std::chrono::microseconds>(StartTimePoint).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::microseconds>(EndTimePoint).time_since_epoch().count();
auto duration = end - start;
std::cout << duration << "us (" << duration * 0.001 << "ms) - STEP_" << ++_step << std::endl;
}
void lap_reset() {
auto EndTimePoint = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<std::chrono::microseconds>(StartTimePoint).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::microseconds>(EndTimePoint).time_since_epoch().count();
auto duration = end - start;
_step = 0;
std::cout << duration << "us (" << duration * 0.001 << "ms) - RESET_STEP_" << _step << std::endl;
StartTimePoint = std::chrono::high_resolution_clock::now();
}
};
|
Praj41/MergeSort_threads
|
RNG.h
|
#include <iostream>
#include <chrono>
#include <random>
long long int* RNG(unsigned int nos = 10, int min = 0, int max = 1000) {
std::random_device rd;
std::mt19937::result_type seed = rd() ^ (
(std::mt19937::result_type)
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()
).count() +
(std::mt19937::result_type)
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count() );
std::mt19937 gen(seed);
std::uniform_int_distribution<long long int> distrib(min, max);
auto *arr = new long long int[nos];
for (unsigned long j = 0; j < nos; ++j)
{
arr[j] = distrib(gen);
}
return arr;
}
long long int RNG_s(int min = 0, int max = 1000) {
std::random_device rd;
std::mt19937::result_type seed = rd() ^ (
(std::mt19937::result_type)
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()
).count() +
(std::mt19937::result_type)
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count() );
std::mt19937 gen(seed);
std::uniform_int_distribution<long long int> distrib(min, max);
return distrib(gen);
}
|
borjaf696/Compact_Flye
|
src/repeat_graph/repeat_resolver.h
|
<gh_stars>0
//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)
//Does the "conventional" resolution of bridged repeats.
//Also, classifies edges into unique and repetitive based
//on read alignment
#pragma once
#include "repeat_graph.h"
#include "read_aligner.h"
#include "multiplicity_inferer.h"
class RepeatResolver
{
public:
RepeatResolver(RepeatGraph& graph, const SequenceContainer& asmSeqs,
const SequenceContainer& readSeqs,
ReadAligner& aligner,
MultiplicityInferer& multInf):
_graph(graph), _asmSeqs(asmSeqs), _readSeqs(readSeqs),
_aligner(aligner), _multInf(multInf) {}
void findRepeats();
void resolveRepeats();
void finalizeGraph();
private:
struct ReadSequence
{
FastaRecord::Id readId;
int32_t start;
int32_t end;
int32_t length() const {return end - start;}
};
struct Connection
{
GraphPath path;
ReadSequence readSeq;
int32_t flankLength;
};
bool checkByReadExtension(const GraphEdge* edge,
const std::vector<GraphAlignment>& alignments);
void clearResolvedRepeats();
std::vector<Connection> getConnections();
int resolveConnections(const std::vector<Connection>& conns,
float minSupport);
void separatePath(const GraphPath& path, EdgeSequence segment,
FastaRecord::Id startId);
RepeatGraph& _graph;
const SequenceContainer& _asmSeqs;
const SequenceContainer& _readSeqs;
ReadAligner& _aligner;
MultiplicityInferer& _multInf;
std::unordered_map<GraphEdge*, int> _substractedCoverage;
};
|
borjaf696/Compact_Flye
|
src/repeat_graph/multiplicity_inferer.h
|
//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)
#pragma once
#include "repeat_graph.h"
#include "read_aligner.h"
//A simple class that assigns edges multiplicity based on the coverage
//and copmutes the mean coverage of all edges
class MultiplicityInferer
{
public:
MultiplicityInferer(RepeatGraph& graph, ReadAligner& aligner,
const SequenceContainer& asmSeqs,
const SequenceContainer& readSeqs):
_graph(graph), _aligner(aligner), _asmSeqs(asmSeqs),
_readSeqs(readSeqs), _uniqueCovThreshold(0), _meanCoverage(0) {}
void estimateCoverage();
int getMeanCoverage() const {return _meanCoverage;}
void removeUnsupportedEdges();
void removeUnsupportedConnections();
void collapseHeterozygousLoops();
void collapseHeterozygousBulges();
void trimTips();
//coverage threshold for an edge to be considered "unique"
int getUniqueCovThreshold() const {return _uniqueCovThreshold;}
private:
RepeatGraph& _graph;
ReadAligner& _aligner;
const SequenceContainer& _asmSeqs;
const SequenceContainer& _readSeqs;
int _uniqueCovThreshold;
int _meanCoverage;
};
|
borjaf696/Compact_Flye
|
src/sequence/Optionk30.h
|
//(c) 2019 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <vector>
#include "unistd.h"
#include "kmer.h"
#include "math.h"
#include <iostream>
#include <fstream>
#include <tuple>
#include <sdsl/int_vector_buffer.hpp>
#include <sdsl/wt_int.hpp>
#include <sdsl/bit_vectors.hpp>
#include <sdsl/int_vector.hpp>
#include <cuckoohash_map.hh>
#define NUM_BITS 3
#define NUM_BITS_FRECS 16
#define POSITION_WRONG 99999
using namespace sdsl;
struct IndexChunk
{
IndexChunk():
hi(0), low(0) {}
IndexChunk(const IndexChunk& other):
hi(other.hi), low(other.low) {}
IndexChunk(IndexChunk&& other):
hi(other.hi), low(other.low) {}
IndexChunk& operator=(const IndexChunk& other)
{
hi = other.hi;
low = other.low;
return *this;
}
size_t get() const
{
return ((size_t)hi << 32) + (size_t)low;
}
void set(size_t val)
{
low = val & ((1ULL << 32) - 1);
hi = val >> 32;
}
uint8_t hi;
uint32_t low;
} __attribute__((packed));
static_assert(sizeof(IndexChunk) == 5,
"Unexpected size of IndexChunk structure");
struct ReadPosition
{
ReadPosition(FastaRecord::Id readId = FastaRecord::ID_NONE,
int32_t position = 0):
readId(readId), position(position) {}
ReadPosition& operator=(const ReadPosition& rp){
this->readId = rp.readId;
this->position = rp.position;
return *this;
}
FastaRecord::Id readId;
int32_t position;
};
struct Read_Pos
{
Read_Pos():size(0),data(nullptr){}
Read_Pos(IndexChunk * rp):size(0),data(rp),frec(0){}
Read_Pos(IndexChunk * rp,size_t frec):size(0),data(rp), frec(frec){}
Read_Pos(size_t frec):size(0), frec(frec){}
uint32_t size, frec;
IndexChunk* data;
};
class Control{
public:
//Little
virtual void insert_alter(Kmer,bool){};
virtual void update_frec(Kmer) {};
virtual size_t size() {return 0;};
virtual size_t size(int) {return 1;};
/*
* New
*/
virtual size_t size_total() {return 1;};
virtual size_t size_total_chunk(size_t) {return 1;};
virtual void internal_count(Kmer) {};
virtual size_t is_unique(size_t, IndexChunk*, size_t pos = 0) {return 1;};
virtual size_t get_frec_solid(size_t, size_t pos = 99999){return 1;};
virtual unsigned int get_sumTotal(){return 0;};
virtual uint32_t getfrec( Kmer, size_t){return -1;};
virtual uint32_t getfrecIn(size_t){return -1;};
virtual unsigned int insert(Kmer) {return 0;};
virtual int locate(Kmer) {return 0;};
virtual int check(Kmer,bool) {return 0;};
virtual void setChunckSize(){};
virtual void mod_frec_pos(Kmer,IndexChunk*){};
virtual void update_read_pos(Kmer, FastaRecord::Id,size_t, size_t){};
virtual Read_Pos * get_pos(Kmer,size_t){return nullptr;};
virtual void set_to_zero(Kmer){};
//Big
virtual void insert(Kmer,bool) {};
virtual void upgrade(bool) {};
virtual void update(Kmer) {};
virtual uint32_t get_frec_int(int,int){return 0;}
virtual Kmer return_kmer(int){return Kmer(0);};
virtual Kmer return_kmer(int,int){return Kmer(0);};
virtual void update(bool){};
virtual bool what(){return false;};
virtual void erase_frec(uint32_t,std::vector<uint32_t>){};
virtual void FinalStep(Kmer,size_t){};
virtual void sortIndexChunks(){};
virtual std::pair<size_t,IndexChunk *> get_kmer_reads(Kmer,size_t){
return std::pair<size_t,IndexChunk *>(0, nullptr);
};
//Destroyer
virtual void clear(){};
};
class BitMap: public Control
{
public:
BitMap();
BitMap(int,size_t);
~BitMap()
{}
void mod_frec_pos(Kmer,IndexChunk*);
void update_read_pos(Kmer,FastaRecord::Id,size_t,size_t);
void insert_alter(Kmer,bool);
void update_frec(Kmer);
void upgrade(bool);
size_t size();
Read_Pos * get_pos(Kmer,size_t);
unsigned int get_sumTotal();
uint32_t getfrec( Kmer, size_t);
uint32_t getfrecIn(size_t);
unsigned int insert(Kmer kmer);
int locate(Kmer kmer);
std::pair<size_t,IndexChunk *> get_kmer_reads(Kmer,size_t);
int check(Kmer,bool);
void setChunckSize();
Kmer return_kmer(int);
void update(bool);
bool what(){
return true;
}
void set_to_zero(Kmer);
void sortIndexChunks()
{
for (auto rp : read_pos)
{
std::sort(rp.data, rp.data + rp.size,
[](const IndexChunk& p1, const IndexChunk& p2)
{return p1.get() < p2.get();});
}
}
void clear();
private:
unsigned int _sumTotal = 0;
void _insert_alter(Kmer kmer, bool){
size_t kmer_repr = kmer.getRepresentation();
for (size_t i = 0; i < b_2.size();i++)
if (!b_2[i][kmer_repr]) {
b_2[i][kmer_repr] = 1;
if (i == (b_2.size()-1)) {
_sumTotal++;
frec.push_back(0);
}
return;
}
return;
}
bit_vector b,_b_final;
rank_support_v<1> b_rank,b_rank_tmp;
select_support_mcl<1> b_select;
std::vector<uint16_t> frec;
std::vector<Read_Pos> read_pos;
std::vector<bit_vector> b_2;
int count = 0;
size_t genome_size = pow(2,30);
};
class BitMapBig: public Control
{
public:
BitMapBig(int,size_t);
void mod_frec_pos(Kmer,IndexChunk*);
void update_read_pos(Kmer,FastaRecord::Id,size_t,size_t);
size_t size();
size_t size(int);
size_t size_total() {
return b_rank_tmp(genome_size);
}
size_t size_total_chunk(size_t chunck)
{
chunck = b_rank_uniques(chunck);
return _info_new_app[chunck].second;
}
void internal_count(Kmer kmer)
{
size_t place = b_rank_tmp(kmer.hash() % (size_t) genome_size);
if (_not_unique[place] == 1)
{
_info_new_app[place].first += _block;
_keys_not_unique[place] = (size_t*)realloc(_keys_not_unique[place]
,_info_new_app[place].first*sizeof(size_t));
_not_unique_read_pos[place] = (Read_Pos*)realloc(_not_unique_read_pos[place]
,_info_new_app[place].first*sizeof(Read_Pos));
}
}
size_t is_unique(size_t place, IndexChunk* rp, size_t pos)
{
if (_not_unique[place] == 0) {
place -= b_rank_uniques(place);
_unique_read_pos[place].data = rp;
return 0;
}
place = b_rank_uniques(place);
_not_unique_read_pos[place][pos].data = rp;
return place;
}
size_t get_frec_solid(size_t place, size_t pos)
{
if (_not_unique[place] == 0)
{
place -= b_rank_uniques(place);
return _unique_read_pos[place].frec;
}
if (pos != 99999) {
place = b_rank_uniques(place);
return _not_unique_read_pos[place][pos].frec;
}
return 0;
}
unsigned int get_sumTotal();
void insert(Kmer,bool);
void upgrade(bool);
void update(Kmer);
Read_Pos * get_pos(Kmer,size_t);
void _insert_2(Kmer);
int check(Kmer,bool);
uint32_t get_frec_int(int, int);
uint32_t getfrec(Kmer,size_t);
std::pair<size_t,IndexChunk *> get_kmer_reads(Kmer,size_t);
Kmer return_kmer(int,int);
void update(bool);
bool what(){return false;}
void clear();
void erase_frec(uint32_t,std::vector<uint32_t>);
void FinalStep(Kmer,size_t);
void sortIndexChunks()
{
for (auto rp : _unique_read_pos)
{
std::sort(rp.data, rp.data + rp.size,
[](const IndexChunk& p1, const IndexChunk& p2)
{return p1.get() < p2.get();});
}
for (size_t i = 0; i < _not_unique_read_pos.size(); ++i)
{
for (size_t j = 0; j < _info_new_app[j].second; ++j)
std::sort(_not_unique_read_pos[i][j].data, _not_unique_read_pos[i][j].data+_not_unique_read_pos[i][j].size,
[](const IndexChunk& p1, const IndexChunk& p2)
{return p1.get() < p2.get();});
}
}
private:
void _initialize_frecs(size_t place, uint32_t frec){
size_t limit_l = _info_frecs[place].second, limit_h = _info_frecs[place].first;
for (size_t i = limit_l; i < limit_h; i++)
_frecs[place][i] = frec;
}
void _insert_1_2(Kmer kmer){
size_t place = kmer.hash() % (size_t) genome_size;
if (bloom[place] == (pow(2,NUM_BITS)-1))
return;
bloom[place]++;
/*if (_h_threshold > 1)
if (b[place] == 1)
return;
if (bloom[place] < _h_threshold)
bloom[place]++;
else
{
_sumsup++;
_sum_unique++;
b[place] = 1;
}*/
/*for (size_t i = 0; i < _h_threshold; i++) {
if (!b_2[i][place]) {
b_2[i][place] = 1;
if (i == (b_2.size() - 1)) {
_sumsup++;
_sum_unique++;
b[place] = 1;
}
return;
}
}*/
return;
}
void _update_2(){
printf("Not supported yet\n");
}
unsigned int _sumsup = 0,_sum_unique = 0, _cont_local = 0, _cuenta_interna,_cuckoos_count = 0;
size_t _h_threshold;
bool _big_genome = false;
rank_support_v<1> b_rank,b_rank_tmp,b_rank_uniques;
bit_vector b,_b_final;
//New Approach
int_vector<NUM_BITS> bloom;
bit_vector _uniques,_not_unique, _uniques_frec, _non_uniques_frec;
std::vector<size_t> _uniques_keys;
std::vector<Read_Pos> _unique_read_pos;
std::vector<size_t *> _keys_not_unique;
std::vector<Read_Pos *> _not_unique_read_pos;
std::vector<bit_vector> b_2;
size_t genome_size = pow(2,30);
//Test arrays
std::vector<size_t> _keys_unique;
std::vector<uint16_t> _frec_unique;
std::vector<uint16_t *> _frecs;
std::vector<size_t *> _keys;
std::vector<std::pair<uint8_t,uint8_t>> _info_frecs, _info_new_app;
uint8_t _block = 1;
//Cuckoos incorporation
cuckoohash_map<Kmer, size_t> _big_case;
};
|
BastienC09/JUCE
|
extras/Projucer/Source/ProjectSaving/jucer_ProjectExport_Xcode.h
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#pragma once
#include "jucer_XcodeProjectParser.h"
//==============================================================================
constexpr auto* macOSArch_Default = "default";
constexpr auto* macOSArch_Native = "Native";
constexpr auto* macOSArch_32BitUniversal = "32BitUniversal";
constexpr auto* macOSArch_64BitUniversal = "64BitUniversal";
constexpr auto* macOSArch_64Bit = "64BitIntel";
//==============================================================================
class XcodeProjectExporter : public ProjectExporter
{
public:
//==============================================================================
static String getDisplayNameMac() { return "Xcode (macOS)"; }
static String getDisplayNameiOS() { return "Xcode (iOS)"; }
static String getTargetFolderNameMac() { return "MacOSX"; }
static String getTargetFolderNameiOS() { return "iOS"; }
static String getValueTreeTypeNameMac() { return "XCODE_MAC"; }
static String getValueTreeTypeNameiOS() { return "XCODE_IPHONE"; }
//==============================================================================
XcodeProjectExporter (Project& p, const ValueTree& t, const bool isIOS)
: ProjectExporter (p, t),
xcodeCanUseDwarf (true),
iOS (isIOS),
applicationCategoryValue (settings, Ids::applicationCategory, getUndoManager(), ""),
customPListValue (settings, Ids::customPList, getUndoManager()),
pListPrefixHeaderValue (settings, Ids::pListPrefixHeader, getUndoManager()),
pListPreprocessValue (settings, Ids::pListPreprocess, getUndoManager()),
subprojectsValue (settings, Ids::xcodeSubprojects, getUndoManager()),
validArchsValue (settings, Ids::xcodeValidArchs, getUndoManager(), getAllArchs(), ","),
extraFrameworksValue (settings, Ids::extraFrameworks, getUndoManager()),
frameworkSearchPathsValue (settings, Ids::frameworkSearchPaths, getUndoManager()),
extraCustomFrameworksValue (settings, Ids::extraCustomFrameworks, getUndoManager()),
embeddedFrameworksValue (settings, Ids::embeddedFrameworks, getUndoManager()),
postbuildCommandValue (settings, Ids::postbuildCommand, getUndoManager()),
prebuildCommandValue (settings, Ids::prebuildCommand, getUndoManager()),
duplicateAppExResourcesFolderValue (settings, Ids::duplicateAppExResourcesFolder, getUndoManager(), true),
iosDeviceFamilyValue (settings, Ids::iosDeviceFamily, getUndoManager(), "1,2"),
iPhoneScreenOrientationValue (settings, Ids::iPhoneScreenOrientation, getUndoManager(), getDefaultScreenOrientations(), ","),
iPadScreenOrientationValue (settings, Ids::iPadScreenOrientation, getUndoManager(), getDefaultScreenOrientations(), ","),
customXcodeResourceFoldersValue (settings, Ids::customXcodeResourceFolders, getUndoManager()),
customXcassetsFolderValue (settings, Ids::customXcassetsFolder, getUndoManager()),
appSandboxValue (settings, Ids::appSandbox, getUndoManager()),
appSandboxInheritanceValue (settings, Ids::appSandboxInheritance, getUndoManager()),
appSandboxOptionsValue (settings, Ids::appSandboxOptions, getUndoManager(), Array<var>(), ","),
hardenedRuntimeValue (settings, Ids::hardenedRuntime, getUndoManager()),
hardenedRuntimeOptionsValue (settings, Ids::hardenedRuntimeOptions, getUndoManager(), Array<var>(), ","),
microphonePermissionNeededValue (settings, Ids::microphonePermissionNeeded, getUndoManager()),
microphonePermissionsTextValue (settings, Ids::microphonePermissionsText, getUndoManager(),
"This app requires audio input. If you do not have an audio interface connected it will use the built-in microphone."),
cameraPermissionNeededValue (settings, Ids::cameraPermissionNeeded, getUndoManager()),
cameraPermissionTextValue (settings, Ids::cameraPermissionText, getUndoManager(),
"This app requires access to the camera to function correctly."),
bluetoothPermissionNeededValue (settings, Ids::iosBluetoothPermissionNeeded, getUndoManager()),
bluetoothPermissionTextValue (settings, Ids::iosBluetoothPermissionText, getUndoManager(),
"This app requires access to Bluetooth to function correctly."),
sendAppleEventsPermissionNeededValue (settings, Ids::sendAppleEventsPermissionNeeded, getUndoManager()),
sendAppleEventsPermissionTextValue (settings, Ids::sendAppleEventsPermissionText, getUndoManager(),
"This app requires the ability to send Apple events to function correctly."),
uiFileSharingEnabledValue (settings, Ids::UIFileSharingEnabled, getUndoManager()),
uiSupportsDocumentBrowserValue (settings, Ids::UISupportsDocumentBrowser, getUndoManager()),
uiStatusBarHiddenValue (settings, Ids::UIStatusBarHidden, getUndoManager()),
uiRequiresFullScreenValue (settings, Ids::UIRequiresFullScreen, getUndoManager(), true),
documentExtensionsValue (settings, Ids::documentExtensions, getUndoManager()),
iosInAppPurchasesValue (settings, Ids::iosInAppPurchases, getUndoManager()),
iosContentSharingValue (settings, Ids::iosContentSharing, getUndoManager(), true),
iosBackgroundAudioValue (settings, Ids::iosBackgroundAudio, getUndoManager()),
iosBackgroundBleValue (settings, Ids::iosBackgroundBle, getUndoManager()),
iosPushNotificationsValue (settings, Ids::iosPushNotifications, getUndoManager()),
iosAppGroupsValue (settings, Ids::iosAppGroups, getUndoManager()),
iCloudPermissionsValue (settings, Ids::iCloudPermissions, getUndoManager()),
networkingMulticastValue (settings, Ids::networkingMulticast, getUndoManager()),
iosDevelopmentTeamIDValue (settings, Ids::iosDevelopmentTeamID, getUndoManager()),
iosAppGroupsIDValue (settings, Ids::iosAppGroupsId, getUndoManager()),
keepCustomXcodeSchemesValue (settings, Ids::keepCustomXcodeSchemes, getUndoManager()),
useHeaderMapValue (settings, Ids::useHeaderMap, getUndoManager()),
customLaunchStoryboardValue (settings, Ids::customLaunchStoryboard, getUndoManager()),
exporterBundleIdentifierValue (settings, Ids::bundleIdentifier, getUndoManager()),
suppressPlistResourceUsageValue (settings, Ids::suppressPlistResourceUsage, getUndoManager()),
useLegacyBuildSystemValue (settings, Ids::useLegacyBuildSystem, getUndoManager()),
buildNumber (settings, Ids::buildNumber, getUndoManager())
{
if (iOS)
{
name = getDisplayNameiOS();
targetLocationValue.setDefault (getDefaultBuildsRootFolder() + getTargetFolderNameiOS());
}
else
{
name = getDisplayNameMac();
targetLocationValue.setDefault (getDefaultBuildsRootFolder() + getTargetFolderNameMac());
}
}
static XcodeProjectExporter* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
{
if (settingsToUse.hasType (getValueTreeTypeNameMac())) return new XcodeProjectExporter (projectToUse, settingsToUse, false);
if (settingsToUse.hasType (getValueTreeTypeNameiOS())) return new XcodeProjectExporter (projectToUse, settingsToUse, true);
return nullptr;
}
//==============================================================================
String getApplicationCategoryString() const { return applicationCategoryValue.get(); }
String getPListToMergeString() const { return customPListValue.get(); }
String getPListPrefixHeaderString() const { return pListPrefixHeaderValue.get(); }
bool isPListPreprocessEnabled() const { return pListPreprocessValue.get(); }
String getSubprojectsString() const { return subprojectsValue.get(); }
String getExtraFrameworksString() const { return extraFrameworksValue.get(); }
String getFrameworkSearchPathsString() const { return frameworkSearchPathsValue.get(); }
String getExtraCustomFrameworksString() const { return extraCustomFrameworksValue.get(); }
String getEmbeddedFrameworksString() const { return embeddedFrameworksValue.get(); }
String getPostBuildScript() const { return postbuildCommandValue.get(); }
String getPreBuildScript() const { return prebuildCommandValue.get(); }
bool shouldDuplicateAppExResourcesFolder() const { return duplicateAppExResourcesFolderValue.get(); }
String getDeviceFamilyString() const { return iosDeviceFamilyValue.get(); }
Array<var> getDefaultScreenOrientations() const { return { "UIInterfaceOrientationPortrait",
"UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight" }; }
Array<var> getAllArchs() const { return { "i386", "x86_64", "arm64", "arm64e"}; }
Array<var> getiPhoneScreenOrientations() const { return *iPhoneScreenOrientationValue.get().getArray(); }
Array<var> getiPadScreenOrientations() const { return *iPadScreenOrientationValue.get().getArray(); }
String getCustomResourceFoldersString() const { return customXcodeResourceFoldersValue.get().toString().replaceCharacters ("\r\n", "::"); }
String getCustomXcassetsFolderString() const { return customXcassetsFolderValue.get(); }
String getCustomLaunchStoryboardString() const { return customLaunchStoryboardValue.get(); }
bool shouldAddStoryboardToProject() const { return getCustomLaunchStoryboardString().isNotEmpty() || getCustomXcassetsFolderString().isEmpty(); }
bool isHardenedRuntimeEnabled() const { return hardenedRuntimeValue.get(); }
Array<var> getHardenedRuntimeOptions() const { return *hardenedRuntimeOptionsValue.get().getArray(); }
bool isAppSandboxEnabled() const { return appSandboxValue.get(); }
bool isAppSandboxInhertianceEnabled() const { return appSandboxInheritanceValue.get(); }
Array<var> getAppSandboxOptions() const { return *appSandboxOptionsValue.get().getArray(); }
Array<var> getValidArchs() const { return *validArchsValue.get().getArray(); }
bool isMicrophonePermissionEnabled() const { return microphonePermissionNeededValue.get(); }
String getMicrophonePermissionsTextString() const { return microphonePermissionsTextValue.get(); }
bool isCameraPermissionEnabled() const { return cameraPermissionNeededValue.get(); }
String getCameraPermissionTextString() const { return cameraPermissionTextValue.get(); }
bool isBluetoothPermissionEnabled() const { return bluetoothPermissionNeededValue.get(); }
String getBluetoothPermissionTextString() const { return bluetoothPermissionTextValue.get(); }
bool isSendAppleEventsPermissionEnabled() const { return sendAppleEventsPermissionNeededValue.get(); }
String getSendAppleEventsPermissionTextString() const { return sendAppleEventsPermissionTextValue.get(); }
bool isInAppPurchasesEnabled() const { return iosInAppPurchasesValue.get(); }
bool isContentSharingEnabled() const { return iosContentSharingValue.get(); }
bool isBackgroundAudioEnabled() const { return iosBackgroundAudioValue.get(); }
bool isBackgroundBleEnabled() const { return iosBackgroundBleValue.get(); }
bool isPushNotificationsEnabled() const { return iosPushNotificationsValue.get(); }
bool isAppGroupsEnabled() const { return iosAppGroupsValue.get(); }
bool isiCloudPermissionsEnabled() const { return iCloudPermissionsValue.get(); }
bool isNetworkingMulticastEnabled() const { return networkingMulticastValue.get(); }
bool isFileSharingEnabled() const { return uiFileSharingEnabledValue.get(); }
bool isDocumentBrowserEnabled() const { return uiSupportsDocumentBrowserValue.get(); }
bool isStatusBarHidden() const { return uiStatusBarHiddenValue.get(); }
bool requiresFullScreen() const { return uiRequiresFullScreenValue.get(); }
bool getSuppressPlistResourceUsage() const { return suppressPlistResourceUsageValue.get(); }
bool shouldUseLegacyBuildSystem() const { return useLegacyBuildSystemValue.get(); }
String getDocumentExtensionsString() const { return documentExtensionsValue.get(); }
bool shouldKeepCustomXcodeSchemes() const { return keepCustomXcodeSchemesValue.get(); }
String getDevelopmentTeamIDString() const { return iosDevelopmentTeamIDValue.get(); }
String getAppGroupIdString() const { return iosAppGroupsIDValue.get(); }
String getBuildNumber() const
{
const auto buildNumberString = buildNumber.get().toString();
return buildNumberString.isNotEmpty() ? buildNumberString : project.getVersionString();
}
String getDefaultLaunchStoryboardName() const { return "LaunchScreen"; }
//==============================================================================
bool usesMMFiles() const override { return true; }
bool canCopeWithDuplicateFiles() override { return true; }
bool supportsUserDefinedConfigurations() const override { return true; }
bool isXcode() const override { return true; }
bool isVisualStudio() const override { return false; }
bool isCodeBlocks() const override { return false; }
bool isMakefile() const override { return false; }
bool isAndroidStudio() const override { return false; }
bool isCLion() const override { return false; }
bool isAndroid() const override { return false; }
bool isWindows() const override { return false; }
bool isLinux() const override { return false; }
bool isOSX() const override { return ! iOS; }
bool isiOS() const override { return iOS; }
Identifier getExporterIdentifier() const override
{
return iOS ? getValueTreeTypeNameiOS() : getValueTreeTypeNameMac();
}
bool supportsPrecompiledHeaders() const override { return true; }
String getNewLineString() const override { return "\n"; }
bool supportsTargetType (build_tools::ProjectType::Target::Type type) const override
{
switch (type)
{
case build_tools::ProjectType::Target::AudioUnitv3PlugIn:
case build_tools::ProjectType::Target::StandalonePlugIn:
case build_tools::ProjectType::Target::GUIApp:
case build_tools::ProjectType::Target::StaticLibrary:
case build_tools::ProjectType::Target::DynamicLibrary:
case build_tools::ProjectType::Target::SharedCodeTarget:
case build_tools::ProjectType::Target::AggregateTarget:
return true;
case build_tools::ProjectType::Target::ConsoleApp:
case build_tools::ProjectType::Target::VSTPlugIn:
case build_tools::ProjectType::Target::VST3PlugIn:
case build_tools::ProjectType::Target::AAXPlugIn:
case build_tools::ProjectType::Target::RTASPlugIn:
case build_tools::ProjectType::Target::AudioUnitPlugIn:
case build_tools::ProjectType::Target::UnityPlugIn:
return ! iOS;
case build_tools::ProjectType::Target::unspecified:
default:
break;
}
return false;
}
void createExporterProperties (PropertyListBuilder& props) override
{
if (iOS)
{
props.add (new TextPropertyComponent (customXcassetsFolderValue, "Custom Xcassets Folder", 128, false),
"If this field is not empty, your Xcode project will use the custom xcassets folder specified here "
"for the app icons and launchimages, and will ignore the Icon files specified above. This will also prevent "
"a launch storyboard from being used.");
props.add (new TextPropertyComponent (customLaunchStoryboardValue, "Custom Launch Storyboard", 256, false),
"If this field is not empty then the specified launch storyboard file will be added to the project as an Xcode "
"resource and will be used for the app's launch screen, otherwise a default blank launch storyboard will be used. "
"The file path should be relative to the project folder.");
}
props.add (new TextPropertyComponent (customXcodeResourceFoldersValue, "Custom Xcode Resource Folders", 8192, true),
"You can specify a list of custom resource folders here (separated by newlines or whitespace). "
"References to these folders will then be added to the Xcode resources. "
"This way you can specify them for OS X and iOS separately, and modify the content of the resource folders "
"without re-saving the Projucer project.");
if (getProject().isAudioPluginProject())
props.add (new ChoicePropertyComponent (duplicateAppExResourcesFolderValue, "Add Duplicate Resources Folder to App Extension"),
"Disable this to prevent the Projucer from creating a duplicate resources folder for AUv3 app extensions.");
props.add (new TextPropertyComponent (buildNumber, "Build Number", 128, false),
"The current version of the project. Used to disambiguate different builds of the same project on App Store Connect. "
"If this field is empty, the project's version will be used as the build number. "
"For more details about the difference between the project version and build version, see developer.apple.com/library/archive/technotes/tn2420/_index.html");
if (iOS)
{
props.add (new ChoicePropertyComponent (iosDeviceFamilyValue, "Device Family",
{ "iPhone", "iPad", "Universal" },
{ "1", "2", "1,2" }),
"The device family to target.");
{
StringArray orientationStrings { "Portrait", "Portrait Upside Down",
"Landscape Left", "Landscape Right" };
Array<var> orientationVars { "UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown",
"UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight" };
props.add (new MultiChoicePropertyComponent (iPhoneScreenOrientationValue, "iPhone Screen Orientation", orientationStrings, orientationVars),
"The screen orientations that this app should support on iPhones.");
props.add (new MultiChoicePropertyComponent (iPadScreenOrientationValue, "iPad Screen Orientation", orientationStrings, orientationVars),
"The screen orientations that this app should support on iPads.");
}
props.add (new ChoicePropertyComponent (uiFileSharingEnabledValue, "File Sharing Enabled"),
"Enable this to expose your app's files to iTunes.");
props.add (new ChoicePropertyComponent (uiSupportsDocumentBrowserValue, "Support Document Browser"),
"Enable this to allow the user to access your app documents from a native file chooser.");
props.add (new ChoicePropertyComponent (uiStatusBarHiddenValue, "Status Bar Hidden"),
"Enable this to disable the status bar in your app.");
props.add (new ChoicePropertyComponent (uiRequiresFullScreenValue, "Requires Full Screen"),
"Disable this to enable non-fullscreen views such as Slide Over or Split View in your app. "
"You will also need to enable all orientations.");
}
else if (projectType.isGUIApplication())
{
props.add (new TextPropertyComponent (documentExtensionsValue, "Document File Extensions", 128, false),
"A comma-separated list of file extensions for documents that your app can open. "
"Using a leading '.' is optional, and the extensions are not case-sensitive.");
}
props.add (new ChoicePropertyComponent (useLegacyBuildSystemValue, "Use Legacy Build System"),
"Enable this to use the deprecated \"Legacy Build System\" in Xcode 10 and above. "
"This may fix build issues that were introduced with the new build system in Xcode 10 and subsequently fixed in Xcode 10.2, "
"however the new build system is recommended for apps targeting Apple silicon.");
if (isOSX())
{
std::vector<std::pair<String, String>> appCategories
{
{ "None", "" },
{ "Business", "business" },
{ "Developer Tools", "developer-tools" },
{ "Education", "education" },
{ "Entertainment", "entertainment" },
{ "Finace", "finance" },
{ "Games", "games" },
{ "Games - Action", "action-games" },
{ "Games - Adventure", "adventure-games" },
{ "Games - Arcade", "arcade-games" },
{ "Games - Board", "board-games" },
{ "Games - Card", "card-games" },
{ "Games - Casino", "casino-games" },
{ "Games - Dice", "dice-games" },
{ "Games - Educational", "educational-games" },
{ "Games - Family", "family-games" },
{ "Games - Kids", "kids-games" },
{ "Games - Music", "music-games" },
{ "Games - Puzzle", "puzzle-games" },
{ "Games - Racing", "racing-games" },
{ "Games - Role Playing", "role-playing-games" },
{ "Games - Simulation", "simulation-games" },
{ "Games - Sports", "sports-games" },
{ "Games - Strategy", "strategy-games" },
{ "Games - Trivia", "trivia-games" },
{ "Games - Word", "word-games" },
{ "Graphics Design", "graphics-design" },
{ "Healthcare & Fitness", "healthcare-fitness" },
{ "Lifestyle", "lifestyle" },
{ "Medial", "medical" },
{ "Music", "music" },
{ "News", "news" },
{ "Photography", "photography" },
{ "Productivity", "productivity" },
{ "Reference", "reference" },
{ "Social Networking", "social-networking" },
{ "Sports", "sports" },
{ "Travel", "travel" },
{ "Utilities", "utilities" },
{ "Video", "video" },
{ "Weather" , "weather" }
};
StringArray appCategoryKeys;
Array<var> appCategoryValues;
for (auto& opt : appCategories)
{
appCategoryKeys.add (opt.first);
if (opt.second.isNotEmpty())
appCategoryValues.add ("public.app-category." + opt.second);
else
appCategoryValues.add ("");
}
props.add (new ChoicePropertyComponent (applicationCategoryValue,
"App Category",
appCategoryKeys,
appCategoryValues),
"The application category.");
props.add (new MultiChoicePropertyComponent (validArchsValue, "Valid Architectures", getAllArchs(), getAllArchs()),
"The full set of architectures which this project may target. "
"Each configuration will build for the intersection of this property, and the per-configuration macOS Architecture property");
props.add (new ChoicePropertyComponent (appSandboxValue, "Use App Sandbox"),
"Enable this to use the app sandbox.");
props.add (new ChoicePropertyComponentWithEnablement (appSandboxInheritanceValue, appSandboxValue, "App Sandbox Inheritance"),
"If app sandbox is enabled, this setting will configure a child process to inherit the sandbox of its parent. "
"Note that if you enable this and have specified any other app sandbox entitlements below, the child process "
"will fail to launch.");
std::vector<std::pair<String, String>> sandboxOptions
{
{ "Network: Incoming Connections (Server)", "network.server" },
{ "Network: Outgoing Connections (Client)", "network.client" },
{ "Hardware: Camera", "device.camera" },
{ "Hardware: Microphone", "device.microphone" },
{ "Hardware: USB", "device.usb" },
{ "Hardware: Printing", "print" },
{ "Hardware: Bluetooth", "device.bluetooth" },
{ "App Data: Contacts", "personal-information.addressbook" },
{ "App Data: Location", "personal-information.location" },
{ "App Data: Calendar", "personal-information.calendars" },
{ "File Access: User Selected File (Read Only)", "files.user-selected.read-only" },
{ "File Access: User Selected File (Read/Write)", "files.user-selected.read-write" },
{ "File Access: Downloads Folder (Read Only)", "files.downloads.read-only" },
{ "File Access: Downloads Folder (Read/Write)", "files.downloads.read-write" },
{ "File Access: Pictures Folder (Read Only)", "files.pictures.read-only" },
{ "File Access: Pictures Folder (Read/Write)", "files.pictures.read-write" },
{ "File Access: Music Folder (Read Only)", "assets.music.read-only" },
{ "File Access: Music Folder (Read/Write)", "assets.music.read-write" },
{ "File Access: Movies Folder (Read Only)", "assets.movies.read-only" },
{ "File Access: Movies Folder (Read/Write)", "assets.movies.read-write" },
{ "Temporary Exception: Audio Unit Hosting", "temporary-exception.audio-unit-host" },
{ "Temporary Exception: Global Mach Service", "temporary-exception.mach-lookup.global-name" },
{ "Temporary Exception: Global Mach Service Dynamic Registration", "temporary-exception.mach-register.global-name" },
{ "Temporary Exception: Home Directory File Access (Read Only)", "temporary-exception.files.home-relative-path.read-only" },
{ "Temporary Exception: Home Directory File Access (Read/Write)", "temporary-exception.files.home-relative-path.read-write" },
{ "Temporary Exception: Absolute Path File Access (Read Only)", "temporary-exception.files.absolute-path.read-only" },
{ "Temporary Exception: Absolute Path File Access (Read/Write)", "temporary-exception.files.absolute-path.read-write" },
{ "Temporary Exception: IOKit User Client Class", "temporary-exception.iokit-user-client-class" },
{ "Temporary Exception: Shared Preference Domain (Read Only)", "temporary-exception.shared-preference.read-only" },
{ "Temporary Exception: Shared Preference Domain (Read/Write)", "temporary-exception.shared-preference.read-write" }
};
StringArray sandboxKeys;
Array<var> sanboxValues;
for (auto& opt : sandboxOptions)
{
sandboxKeys.add (opt.first);
sanboxValues.add ("com.apple.security." + opt.second);
}
props.add (new MultiChoicePropertyComponentWithEnablement (appSandboxOptionsValue,
appSandboxValue,
"App Sandbox Options",
sandboxKeys,
sanboxValues));
props.add (new ChoicePropertyComponent (hardenedRuntimeValue, "Use Hardened Runtime"),
"Enable this to use the hardened runtime required for app notarization.");
std::vector<std::pair<String, String>> hardeningOptions
{
{ "Runtime Exceptions: Allow Execution of JIT-compiled Code", "cs.allow-jit" },
{ "Runtime Exceptions: Allow Unsigned Executable Memory", "cs.allow-unsigned-executable-memory" },
{ "Runtime Exceptions: Allow DYLD Environment Variables", "cs.allow-dyld-environment-variables" },
{ "Runtime Exceptions: Disable Library Validation", "cs.disable-library-validation" },
{ "Runtime Exceptions: Disable Executable Memory Protection", "cs.disable-executable-page-protection" },
{ "Runtime Exceptions: Debugging Tool", "cs.debugger" },
{ "Resource Access: Audio Input", "device.audio-input" },
{ "Resource Access: Camera", "device.camera" },
{ "Resource Access: Location", "personal-information.location" },
{ "Resource Access: Address Book", "personal-information.addressbook" },
{ "Resource Access: Calendar", "personal-information.calendars" },
{ "Resource Access: Photos Library", "personal-information.photos-library" },
{ "Resource Access: Apple Events", "automation.apple-events" }
};
StringArray hardeningKeys;
Array<var> hardeningValues;
for (auto& opt : hardeningOptions)
{
hardeningKeys.add (opt.first);
hardeningValues.add ("com.apple.security." + opt.second);
}
props.add (new MultiChoicePropertyComponentWithEnablement (hardenedRuntimeOptionsValue,
hardenedRuntimeValue,
"Hardened Runtime Options",
hardeningKeys,
hardeningValues));
}
props.add (new ChoicePropertyComponent (microphonePermissionNeededValue, "Microphone Access"),
"Enable this to allow your app to use the microphone. "
"The user of your app will be prompted to grant microphone access permissions.");
props.add (new TextPropertyComponentWithEnablement (microphonePermissionsTextValue, microphonePermissionNeededValue,
"Microphone Access Text", 1024, false),
"A short description of why your app requires microphone access.");
props.add (new ChoicePropertyComponent (cameraPermissionNeededValue, "Camera Access"),
"Enable this to allow your app to use the camera. "
"The user of your app will be prompted to grant camera access permissions.");
props.add (new TextPropertyComponentWithEnablement (cameraPermissionTextValue, cameraPermissionNeededValue,
"Camera Access Text", 1024, false),
"A short description of why your app requires camera access.");
props.add (new ChoicePropertyComponent (bluetoothPermissionNeededValue, "Bluetooth Access"),
"Enable this to allow your app to use Bluetooth on iOS 13.0 and above, and macOS 11.0 and above. "
"The user of your app will be prompted to grant Bluetooth access permissions.");
props.add (new TextPropertyComponentWithEnablement (bluetoothPermissionTextValue, bluetoothPermissionNeededValue,
"Bluetooth Access Text", 1024, false),
"A short description of why your app requires Bluetooth access.");
if (! iOS)
{
props.add (new ChoicePropertyComponent (sendAppleEventsPermissionNeededValue, "Send Apple Events"),
"Enable this to allow your app to send Apple events. "
"The user of your app will be prompted to grant permissions to control other apps.");
props.add (new TextPropertyComponentWithEnablement (sendAppleEventsPermissionTextValue, sendAppleEventsPermissionNeededValue,
"Send Apple Events Text", 1024, false),
"A short description of why your app requires the ability to send Apple events.");
}
props.add (new ChoicePropertyComponent (iosInAppPurchasesValue, "In-App Purchases Capability"),
"Enable this to grant your app the capability for in-app purchases. "
"This option requires that you specify a valid Development Team ID.");
if (iOS)
{
props.add (new ChoicePropertyComponent (iosContentSharingValue, "Content Sharing"),
"Enable this to allow your app to share content with other apps.");
props.add (new ChoicePropertyComponent (iosBackgroundAudioValue, "Audio Background Capability"),
"Enable this to grant your app the capability to access audio when in background mode. "
"This permission is required if your app creates a MIDI input or output device.");
props.add (new ChoicePropertyComponent (iosBackgroundBleValue, "Bluetooth MIDI Background Capability"),
"Enable this to grant your app the capability to connect to Bluetooth LE devices when in background mode.");
props.add (new ChoicePropertyComponent (iosAppGroupsValue, "App Groups Capability"),
"Enable this to grant your app the capability to share resources between apps using the same app group ID.");
props.add (new ChoicePropertyComponent (iCloudPermissionsValue, "iCloud Permissions"),
"Enable this to grant your app the capability to use native file load/save browser windows on iOS.");
}
props.add (new ChoicePropertyComponent (networkingMulticastValue, "Networking Multicast Capability"),
"Your app must have this entitlement to send or receive IP multicast or broadcast. "
"You will also need permission from Apple to use this entitlement.");
props.add (new ChoicePropertyComponent (iosPushNotificationsValue, "Push Notifications Capability"),
"Enable this to grant your app the capability to receive push notifications.");
props.add (new TextPropertyComponent (customPListValue, "Custom PList", 8192, true),
"You can paste the contents of an XML PList file in here, and the settings that it contains will override any "
"settings that the Projucer creates. BEWARE! When doing this, be careful to remove from the XML any "
"values that you DO want the Projucer to change!");
props.add (new ChoicePropertyComponent (pListPreprocessValue, "PList Preprocess"),
"Enable this to preprocess PList file. This will allow you to set values to preprocessor defines,"
" for instance if you define: #define MY_FLAG 1 in a prefix header file (see PList prefix header), you can have"
" a key with MY_FLAG value and it will be replaced with 1.");
props.add (new TextPropertyComponent (pListPrefixHeaderValue, "PList Prefix Header", 512, false),
"Header file containing definitions used in plist file (see PList Preprocess).");
props.add (new ChoicePropertyComponent (suppressPlistResourceUsageValue, "Suppress AudioUnit Plist resourceUsage Key"),
"Suppress the resourceUsage key in the target's generated Plist. This is useful for AU"
" plugins that must access resources which cannot be declared in the resourceUsage block, such"
" as UNIX domain sockets. In particular, PACE-protected AU plugins may require this option to be enabled"
" in order for the plugin to load in GarageBand.");
props.add (new TextPropertyComponent (extraFrameworksValue, "Extra System Frameworks", 2048, false),
"A comma-separated list of extra system frameworks that should be added to the build. "
"(Don't include the .framework extension in the name)"
" The frameworks are expected to be located in /System/Library/Frameworks");
props.add (new TextPropertyComponent (frameworkSearchPathsValue, "Framework Search Paths", 8192, true),
"A set of paths to search for custom frameworks (one per line).");
props.add (new TextPropertyComponent (extraCustomFrameworksValue, "Extra Custom Frameworks", 8192, true),
"Paths to custom frameworks that should be added to the build (one per line). "
"You will probably need to add an entry to the Framework Search Paths for each unique directory.");
props.add (new TextPropertyComponent (embeddedFrameworksValue, "Embedded Frameworks", 8192, true),
"Paths to frameworks to be embedded with the app (one per line). "
"If you are adding a framework here then you do not need to specify it in Extra Custom Frameworks too. "
"You will probably need to add an entry to the Framework Search Paths for each unique directory.");
props.add (new TextPropertyComponent (subprojectsValue, "Xcode Subprojects", 8192, true),
"Paths to Xcode projects that should be added to the build (one per line). "
"These can be absolute or relative to the build directory. "
"The names of the required build products can be specified after a colon, comma separated, "
"e.g. \"path/to/MySubProject.xcodeproj: MySubProject, OtherTarget\". "
"If no build products are specified, all build products associated with a subproject will be added.");
props.add (new TextPropertyComponent (prebuildCommandValue, "Pre-Build Shell Script", 32768, true),
"Some shell-script that will be run before a build starts.");
props.add (new TextPropertyComponent (postbuildCommandValue, "Post-Build Shell Script", 32768, true),
"Some shell-script that will be run after a build completes.");
props.add (new TextPropertyComponent (exporterBundleIdentifierValue, "Exporter Bundle Identifier", 256, false),
"Use this to override the project bundle identifier for this exporter. "
"This is useful if you want to use different bundle identifiers for Mac and iOS exporters in the same project.");
props.add (new TextPropertyComponent (iosDevelopmentTeamIDValue, "Development Team ID", 10, false),
"The Team ID to be used for setting up code-signing for your application. "
"This is a ten-character string (for example \"S7B6T5XJ2Q\") that can be found under the \"Organisational Unit\" "
"field of your developer certificate in Keychain Access or in the membership page of your account on developer.apple.com.");
if (iOS)
props.add (new TextPropertyComponentWithEnablement (iosAppGroupsIDValue, iosAppGroupsValue, "App Group ID", 256, false),
"The App Group ID to be used for allowing multiple apps to access a shared resource folder. Multiple IDs can be "
"added separated by a semicolon.");
props.add (new ChoicePropertyComponent (keepCustomXcodeSchemesValue, "Keep Custom Xcode Schemes"),
"Enable this to keep any Xcode schemes you have created for debugging or running, e.g. to launch a plug-in in"
"various hosts. If disabled, all schemes are replaced by a default set.");
props.add (new ChoicePropertyComponent (useHeaderMapValue, "USE_HEADERMAP"),
"Enable this to make Xcode search all the projects folders for include files. This means you can be lazy "
"and not bother using relative paths to include your headers, but it means your code won't be "
"compatible with other build systems");
}
bool launchProject() override
{
#if JUCE_MAC
return getProjectBundle().startAsProcess();
#else
return false;
#endif
}
bool canLaunchProject() override
{
#if JUCE_MAC
return true;
#else
return false;
#endif
}
//==============================================================================
void create (const OwnedArray<LibraryModule>&) const override
{
for (auto& target : targets)
if (target->shouldCreatePList())
target->infoPlistFile = getTargetFolder().getChildFile (target->getInfoPlistName());
menuNibFile = getTargetFolder().getChildFile ("RecentFilesMenuTemplate.nib");
createIconFile();
auto projectBundle = getProjectBundle();
createDirectoryOrThrow (projectBundle);
createObjects();
build_tools::writeStreamToFile (projectBundle.getChildFile ("project.pbxproj"),
[this] (MemoryOutputStream& mo) { writeProjectFile (mo); });
writeInfoPlistFiles();
writeWorkspaceSettings();
// Deleting the .rsrc files can be needed to force Xcode to update the version number.
deleteRsrcFiles (getTargetFolder().getChildFile ("build"));
}
//==============================================================================
void addPlatformSpecificSettingsForProjectType (const build_tools::ProjectType&) override
{
callForAllSupportedTargets ([this] (build_tools::ProjectType::Target::Type targetType)
{
targets.insert (targetType == build_tools::ProjectType::Target::AggregateTarget ? 0 : -1,
new XcodeTarget (targetType, *this));
});
// If you hit this assert, you tried to generate a project for an exporter
// that does not support any of your targets!
jassert (targets.size() > 0);
}
void updateDeprecatedSettings() override
{
if (iOS)
updateOldOrientationSettings();
}
void updateDeprecatedSettingsInteractively() override
{
if (hasInvalidPostBuildScript())
{
String alertWindowText = iOS ? "Your Xcode (iOS) Exporter settings use an invalid post-build script. Click 'Update' to remove it."
: "Your Xcode (macOS) Exporter settings use a pre-JUCE 4.2 post-build script to move the plug-in binaries to their plug-in install folders.\n\n"
"Since JUCE 4.2, this is instead done using \"AU/VST/VST2/AAX/RTAS Binary Location\" in the Xcode (OS X) configuration settings.\n\n"
"Click 'Update' to remove the script (otherwise your plug-in may not compile correctly).";
if (AlertWindow::showOkCancelBox (MessageBoxIconType::WarningIcon,
"Project settings: " + project.getDocumentTitle(),
alertWindowText, "Update", "Cancel", nullptr, nullptr))
postbuildCommandValue.resetToDefault();
}
}
bool hasInvalidPostBuildScript() const
{
// check whether the script is identical to the old one that the Introjucer used to auto-generate
return (MD5 (getPostBuildScript().toUTF8()).toHexString() == "265ac212a7e734c5bbd6150e1eae18a1");
}
//==============================================================================
void initialiseDependencyPathValues() override
{
vstLegacyPathValueWrapper.init ({ settings, Ids::vstLegacyFolder, nullptr },
getAppSettings().getStoredPath (Ids::vstLegacyPath, TargetOS::osx), TargetOS::osx);
aaxPathValueWrapper.init ({ settings, Ids::aaxFolder, nullptr },
getAppSettings().getStoredPath (Ids::aaxPath, TargetOS::osx), TargetOS::osx);
rtasPathValueWrapper.init ({ settings, Ids::rtasFolder, nullptr },
getAppSettings().getStoredPath (Ids::rtasPath, TargetOS::osx), TargetOS::osx);
}
protected:
//==============================================================================
class XcodeBuildConfiguration : public BuildConfiguration,
private ValueTree::Listener
{
public:
XcodeBuildConfiguration (Project& p, const ValueTree& t, const bool isIOS, const ProjectExporter& e)
: BuildConfiguration (p, t, e),
iOS (isIOS),
macOSBaseSDK (config, Ids::macOSBaseSDK, getUndoManager()),
macOSDeploymentTarget (config, Ids::macOSDeploymentTarget, getUndoManager(), "10.11"),
macOSArchitecture (config, Ids::osxArchitecture, getUndoManager(), macOSArch_Default),
iosBaseSDK (config, Ids::iosBaseSDK, getUndoManager()),
iosDeploymentTarget (config, Ids::iosDeploymentTarget, getUndoManager(), "9.3"),
customXcodeFlags (config, Ids::customXcodeFlags, getUndoManager()),
plistPreprocessorDefinitions (config, Ids::plistPreprocessorDefinitions, getUndoManager()),
codeSignIdentity (config, Ids::codeSigningIdentity, getUndoManager()),
fastMathEnabled (config, Ids::fastMath, getUndoManager()),
stripLocalSymbolsEnabled (config, Ids::stripLocalSymbols, getUndoManager()),
pluginBinaryCopyStepEnabled (config, Ids::enablePluginBinaryCopyStep, getUndoManager(), true),
vstBinaryLocation (config, Ids::vstBinaryLocation, getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/VST/"),
vst3BinaryLocation (config, Ids::vst3BinaryLocation, getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/VST3/"),
auBinaryLocation (config, Ids::auBinaryLocation, getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/Components/"),
rtasBinaryLocation (config, Ids::rtasBinaryLocation, getUndoManager(), "/Library/Application Support/Digidesign/Plug-Ins/"),
aaxBinaryLocation (config, Ids::aaxBinaryLocation, getUndoManager(), "/Library/Application Support/Avid/Audio/Plug-Ins/"),
unityPluginBinaryLocation (config, Ids::unityPluginBinaryLocation, getUndoManager())
{
updateOldPluginBinaryLocations();
updateOldSDKDefaults();
optimisationLevelValue.setDefault (isDebug() ? gccO0 : gccO3);
config.addListener (this);
}
//==============================================================================
void createConfigProperties (PropertyListBuilder& props) override
{
if (project.isAudioPluginProject())
addXcodePluginInstallPathProperties (props);
addRecommendedLLVMCompilerWarningsProperty (props);
addGCCOptimisationProperty (props);
const String sdkInfoString ("\nThis must be in the format major.minor and contain only the numeric version number. "
"If this is left empty then the default will be used."
"\nThe minimum supported version is ");
if (iOS)
{
props.add (new TextPropertyComponent (iosBaseSDK, "iOS Base SDK", 8, false),
"The version of the iOS SDK to link against." + sdkInfoString + "9.3.");
props.add (new TextPropertyComponent (iosDeploymentTarget, "iOS Deployment Target", 8, false),
"The minimum version of iOS to target." + sdkInfoString + "9.0.");
}
else
{
props.add (new TextPropertyComponent (macOSBaseSDK, "macOS Base SDK", 8, false),
"The version of the macOS SDK to link against." + sdkInfoString + "10.11.");
props.add (new TextPropertyComponent (macOSDeploymentTarget, "macOS Deployment Target", 8, false),
"The minimum version of macOS to target." + sdkInfoString + "10.7.");
props.add (new ChoicePropertyComponent (macOSArchitecture, "macOS Architecture",
{ "Native architecture of build machine", "Standard 32-bit", "Standard 32/64-bit", "Standard 64-bit" },
{ macOSArch_Native, macOSArch_32BitUniversal, macOSArch_64BitUniversal, macOSArch_64Bit }),
"The type of macOS binary that will be produced.");
}
props.add (new TextPropertyComponent (customXcodeFlags, "Custom Xcode Flags", 8192, true),
"A comma-separated list of custom Xcode setting flags which will be appended to the list of generated flags, "
"e.g. MACOSX_DEPLOYMENT_TARGET_i386 = 10.5");
props.add (new TextPropertyComponent (plistPreprocessorDefinitions, "PList Preprocessor Definitions", 2048, true),
"Preprocessor definitions used during PList preprocessing (see PList Preprocess).");
props.add (new TextPropertyComponent (codeSignIdentity, "Code-Signing Identity", 1024, false),
"The name of a code-signing identity for Xcode to apply.");
props.add (new ChoicePropertyComponent (fastMathEnabled, "Relax IEEE Compliance"),
"Enable this to use FAST_MATH non-IEEE mode. (Warning: this can have unexpected results!)");
props.add (new ChoicePropertyComponent (stripLocalSymbolsEnabled, "Strip Local Symbols"),
"Enable this to strip any locally defined symbols resulting in a smaller binary size. Enabling this "
"will also remove any function names from crash logs. Must be disabled for static library projects. "
"Note that disabling this will not necessarily generate full debug symbols. For release configs, "
"you will also need to add the following to the \"Custom Xcode Flags\" field: "
"GCC_GENERATE_DEBUGGING_SYMBOLS = YES, STRIP_INSTALLED_PRODUCT = NO, COPY_PHASE_STRIP = NO");
}
String getModuleLibraryArchName() const override
{
return "${CURRENT_ARCH}";
}
//==============================================================================
String getMacOSArchitectureString() const { return macOSArchitecture.get(); }
String getPListPreprocessorDefinitionsString() const { return plistPreprocessorDefinitions.get(); }
bool isFastMathEnabled() const { return fastMathEnabled.get(); }
bool isStripLocalSymbolsEnabled() const { return stripLocalSymbolsEnabled.get(); }
String getCustomXcodeFlagsString() const { return customXcodeFlags.get(); }
String getMacOSBaseSDKString() const { return macOSBaseSDK.get(); }
String getMacOSDeploymentTargetString() const { return macOSDeploymentTarget.get(); }
String getCodeSignIdentityString() const { return codeSignIdentity.get(); }
String getiOSBaseSDKString() const { return iosBaseSDK.get(); }
String getiOSDeploymentTargetString() const { return iosDeploymentTarget.get(); }
bool isPluginBinaryCopyStepEnabled() const { return pluginBinaryCopyStepEnabled.get(); }
String getVSTBinaryLocationString() const { return vstBinaryLocation.get(); }
String getVST3BinaryLocationString() const { return vst3BinaryLocation.get(); }
String getAUBinaryLocationString() const { return auBinaryLocation.get(); }
String getRTASBinaryLocationString() const { return rtasBinaryLocation.get();}
String getAAXBinaryLocationString() const { return aaxBinaryLocation.get();}
String getUnityPluginBinaryLocationString() const { return unityPluginBinaryLocation.get(); }
private:
//==============================================================================
bool iOS;
ValueWithDefault macOSBaseSDK, macOSDeploymentTarget, macOSArchitecture, iosBaseSDK, iosDeploymentTarget,
customXcodeFlags, plistPreprocessorDefinitions, codeSignIdentity,
fastMathEnabled, stripLocalSymbolsEnabled, pluginBinaryCopyStepEnabled,
vstBinaryLocation, vst3BinaryLocation, auBinaryLocation, rtasBinaryLocation,
aaxBinaryLocation, unityPluginBinaryLocation;
//==============================================================================
void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
{
const auto updateOldSDKSetting = [this] (const Identifier& oldProperty,
const String& sdkString,
const String& sdkSuffix)
{
if (sdkString.isEmpty())
config.removeProperty (oldProperty, nullptr);
else
config.setProperty (oldProperty, sdkString + sdkSuffix, nullptr);
};
if (property == Ids::macOSBaseSDK)
updateOldSDKSetting (Ids::osxSDK, macOSBaseSDK.get(), " SDK");
else if (property == Ids::macOSDeploymentTarget)
updateOldSDKSetting (Ids::osxCompatibility, macOSDeploymentTarget.get(), " SDK");
else if (property == Ids::iosDeploymentTarget)
updateOldSDKSetting (Ids::iosCompatibility, iosDeploymentTarget.get(), {});
}
void addXcodePluginInstallPathProperties (PropertyListBuilder& props)
{
auto isBuildingAnyPlugins = (project.shouldBuildVST() || project.shouldBuildVST3() || project.shouldBuildAU()
|| project.shouldBuildRTAS() || project.shouldBuildAAX() || project.shouldBuildUnityPlugin());
if (isBuildingAnyPlugins)
props.add (new ChoicePropertyComponent (pluginBinaryCopyStepEnabled, "Enable Plugin Copy Step"),
"Enable this to copy plugin binaries to the specified folder after building.");
if (project.shouldBuildVST3())
props.add (new TextPropertyComponentWithEnablement (vst3BinaryLocation, pluginBinaryCopyStepEnabled, "VST3 Binary Location",
1024, false),
"The folder in which the compiled VST3 binary should be placed.");
if (project.shouldBuildAU())
props.add (new TextPropertyComponentWithEnablement (auBinaryLocation, pluginBinaryCopyStepEnabled, "AU Binary Location",
1024, false),
"The folder in which the compiled AU binary should be placed.");
if (project.shouldBuildRTAS())
props.add (new TextPropertyComponentWithEnablement (rtasBinaryLocation, pluginBinaryCopyStepEnabled, "RTAS Binary Location",
1024, false),
"The folder in which the compiled RTAS binary should be placed.");
if (project.shouldBuildAAX())
props.add (new TextPropertyComponentWithEnablement (aaxBinaryLocation, pluginBinaryCopyStepEnabled, "AAX Binary Location",
1024, false),
"The folder in which the compiled AAX binary should be placed.");
if (project.shouldBuildUnityPlugin())
props.add (new TextPropertyComponentWithEnablement (unityPluginBinaryLocation, pluginBinaryCopyStepEnabled, "Unity Binary Location",
1024, false),
"The folder in which the compiled Unity plugin binary and associated C# GUI script should be placed.");
if (project.shouldBuildVST())
props.add (new TextPropertyComponentWithEnablement (vstBinaryLocation, pluginBinaryCopyStepEnabled, "VST Binary Location",
1024, false),
"The folder in which the compiled legacy VST binary should be placed.");
}
void updateOldPluginBinaryLocations()
{
if (! config ["xcodeVstBinaryLocation"].isVoid()) vstBinaryLocation = config ["xcodeVstBinaryLocation"];
if (! config ["xcodeVst3BinaryLocation"].isVoid()) vst3BinaryLocation = config ["xcodeVst3BinaryLocation"];
if (! config ["xcodeAudioUnitBinaryLocation"].isVoid()) auBinaryLocation = config ["xcodeAudioUnitBinaryLocation"];
if (! config ["xcodeRtasBinaryLocation"].isVoid()) rtasBinaryLocation = config ["xcodeRtasBinaryLocation"];
if (! config ["xcodeAaxBinaryLocation"].isVoid()) aaxBinaryLocation = config ["xcodeAaxBinaryLocation"];
}
void updateOldSDKDefaults()
{
if (macOSArchitecture.get() == "default")
macOSArchitecture.resetToDefault();
const auto updateSDKString = [this] (const Identifier& propertyName, ValueWithDefault& value, const String& suffix)
{
auto sdkString = config[propertyName].toString();
if (sdkString == "default")
value.resetToDefault();
else if (sdkString.isNotEmpty() && sdkString.endsWith (suffix))
value = sdkString.upToLastOccurrenceOf (suffix, false, false);
};
updateSDKString (Ids::osxSDK, macOSBaseSDK, " SDK");
updateSDKString (Ids::osxCompatibility, macOSDeploymentTarget, " SDK");
updateSDKString (Ids::iosCompatibility, iosDeploymentTarget, {});
}
};
BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
{
return *new XcodeBuildConfiguration (project, v, iOS, *this);
}
public:
//==============================================================================
/* The numbers for these enum values are defined by Xcode for the different
possible destinations of a "copy files" post-build step.
*/
enum XcodeCopyFilesDestinationIDs
{
kWrapperFolder = 1,
kExecutablesFolder = 6,
kResourcesFolder = 7,
kFrameworksFolder = 10,
kSharedFrameworksFolder = 11,
kSharedSupportFolder = 12,
kPluginsFolder = 13,
kJavaResourcesFolder = 15,
kXPCServicesFolder = 16
};
//==============================================================================
struct XcodeTarget : build_tools::ProjectType::Target
{
//==============================================================================
XcodeTarget (build_tools::ProjectType::Target::Type targetType, const XcodeProjectExporter& exporter)
: Target (targetType),
owner (exporter)
{
switch (type)
{
case GUIApp:
xcodeFileType = "wrapper.application";
xcodeBundleExtension = ".app";
xcodeProductType = "com.apple.product-type.application";
xcodeCopyToProductInstallPathAfterBuild = false;
break;
case ConsoleApp:
xcodeFileType = "compiled.mach-o.executable";
xcodeBundleExtension = String();
xcodeProductType = "com.apple.product-type.tool";
xcodeCopyToProductInstallPathAfterBuild = false;
break;
case StaticLibrary:
xcodeFileType = "archive.ar";
xcodeBundleExtension = ".a";
xcodeProductType = "com.apple.product-type.library.static";
xcodeCopyToProductInstallPathAfterBuild = false;
break;
case DynamicLibrary:
xcodeFileType = "compiled.mach-o.dylib";
xcodeProductType = "com.apple.product-type.library.dynamic";
xcodeBundleExtension = ".dylib";
xcodeCopyToProductInstallPathAfterBuild = false;
break;
case VSTPlugIn:
xcodeFileType = "wrapper.cfbundle";
xcodeBundleExtension = ".vst";
xcodeProductType = "com.apple.product-type.bundle";
xcodeCopyToProductInstallPathAfterBuild = true;
break;
case VST3PlugIn:
xcodeFileType = "wrapper.cfbundle";
xcodeBundleExtension = ".vst3";
xcodeProductType = "com.apple.product-type.bundle";
xcodeCopyToProductInstallPathAfterBuild = true;
break;
case AudioUnitPlugIn:
xcodeFileType = "wrapper.cfbundle";
xcodeBundleExtension = ".component";
xcodeProductType = "com.apple.product-type.bundle";
xcodeCopyToProductInstallPathAfterBuild = true;
addExtraAudioUnitTargetSettings();
break;
case StandalonePlugIn:
xcodeFileType = "wrapper.application";
xcodeBundleExtension = ".app";
xcodeProductType = "com.apple.product-type.application";
xcodeCopyToProductInstallPathAfterBuild = false;
break;
case AudioUnitv3PlugIn:
xcodeFileType = "wrapper.app-extension";
xcodeBundleExtension = ".appex";
xcodeBundleIDSubPath = "AUv3";
xcodeProductType = "com.apple.product-type.app-extension";
xcodeCopyToProductInstallPathAfterBuild = false;
addExtraAudioUnitv3PlugInTargetSettings();
break;
case AAXPlugIn:
xcodeFileType = "wrapper.cfbundle";
xcodeBundleExtension = ".aaxplugin";
xcodeProductType = "com.apple.product-type.bundle";
xcodeCopyToProductInstallPathAfterBuild = true;
break;
case RTASPlugIn:
xcodeFileType = "wrapper.cfbundle";
xcodeBundleExtension = ".dpm";
xcodeProductType = "com.apple.product-type.bundle";
xcodeCopyToProductInstallPathAfterBuild = true;
break;
case UnityPlugIn:
xcodeFileType = "wrapper.cfbundle";
xcodeBundleExtension = ".bundle";
xcodeProductType = "com.apple.product-type.bundle";
xcodeCopyToProductInstallPathAfterBuild = true;
break;
case SharedCodeTarget:
xcodeFileType = "archive.ar";
xcodeBundleExtension = ".a";
xcodeProductType = "com.apple.product-type.library.static";
xcodeCopyToProductInstallPathAfterBuild = false;
break;
case AggregateTarget:
xcodeCopyToProductInstallPathAfterBuild = false;
break;
case unspecified:
default:
// unknown target type!
jassertfalse;
break;
}
}
String getXcodeSchemeName() const
{
return owner.projectName + " - " + getName();
}
String getID() const
{
return owner.createID (String ("__target") + getName());
}
String getInfoPlistName() const
{
return String ("Info-") + String (getName()).replace (" ", "_") + String (".plist");
}
String getEntitlementsFilename() const
{
return String (getName()).replace (" ", "_") + String (".entitlements");
}
String xcodeBundleExtension;
String xcodeProductType, xcodeFileType;
String xcodeOtherRezFlags, xcodeBundleIDSubPath;
bool xcodeCopyToProductInstallPathAfterBuild;
StringArray xcodeFrameworks, xcodeLibs;
Array<XmlElement> xcodeExtraPListEntries;
StringArray frameworkIDs, buildPhaseIDs, configIDs, sourceIDs, rezFileIDs, dependencyIDs;
StringArray frameworkNames;
String mainBuildProductID;
File infoPlistFile;
struct SourceFileInfo
{
build_tools::RelativePath path;
bool shouldBeCompiled = false;
};
Array<SourceFileInfo> getSourceFilesInfo (const Project::Item& projectItem) const
{
Array<SourceFileInfo> result;
auto targetType = (owner.getProject().isAudioPluginProject() ? type : SharedCodeTarget);
if (projectItem.isGroup())
{
for (int i = 0; i < projectItem.getNumChildren(); ++i)
result.addArray (getSourceFilesInfo (projectItem.getChild (i)));
}
else if (projectItem.shouldBeAddedToTargetProject() && projectItem.shouldBeAddedToTargetExporter (owner)
&& owner.getProject().getTargetTypeFromFilePath (projectItem.getFile(), true) == targetType)
{
SourceFileInfo info;
info.path = build_tools::RelativePath (projectItem.getFile(),
owner.getTargetFolder(),
build_tools::RelativePath::buildTargetFolder);
jassert (info.path.getRoot() == build_tools::RelativePath::buildTargetFolder);
if (targetType == SharedCodeTarget || projectItem.shouldBeCompiled())
info.shouldBeCompiled = projectItem.shouldBeCompiled();
result.add (info);
}
return result;
}
//==============================================================================
void addMainBuildProduct() const
{
jassert (xcodeFileType.isNotEmpty());
jassert (xcodeBundleExtension.isEmpty() || xcodeBundleExtension.startsWithChar ('.'));
if (ProjectExporter::BuildConfiguration::Ptr config = owner.getConfiguration (0))
{
auto productName = owner.replacePreprocessorTokens (*config, config->getTargetBinaryNameString (type == UnityPlugIn));
if (xcodeFileType == "archive.ar")
productName = getStaticLibbedFilename (productName);
else
productName += xcodeBundleExtension;
addBuildProduct (xcodeFileType, productName);
}
}
//==============================================================================
void addBuildProduct (const String& fileType, const String& binaryName) const
{
ValueTree v (owner.createID (String ("__productFileID") + getName()) + " /* " + getName() + " */");
v.setProperty ("isa", "PBXFileReference", nullptr);
v.setProperty ("explicitFileType", fileType, nullptr);
v.setProperty ("includeInIndex", (int) 0, nullptr);
v.setProperty ("path", binaryName, nullptr);
v.setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);
owner.addObject (v);
}
//==============================================================================
String addDependencyFor (const XcodeTarget& dependentTarget)
{
auto dependencyID = owner.createID (String ("__dependency") + getName() + dependentTarget.getName());
ValueTree v (dependencyID);
v.setProperty ("isa", "PBXTargetDependency", nullptr);
v.setProperty ("target", getID(), nullptr);
owner.addObject (v);
return dependencyID;
}
void addDependencies()
{
if (! owner.project.isAudioPluginProject())
return;
if (type == XcodeTarget::StandalonePlugIn) // depends on AUv3 and shared code
{
if (auto* auv3Target = owner.getTargetOfType (XcodeTarget::AudioUnitv3PlugIn))
dependencyIDs.add (auv3Target->addDependencyFor (*this));
if (auto* sharedCodeTarget = owner.getTargetOfType (XcodeTarget::SharedCodeTarget))
dependencyIDs.add (sharedCodeTarget->addDependencyFor (*this));
}
else if (type == XcodeTarget::AggregateTarget) // depends on all other targets
{
for (auto* target : owner.targets)
if (target->type != XcodeTarget::AggregateTarget)
dependencyIDs.add (target->addDependencyFor (*this));
}
else if (type != XcodeTarget::SharedCodeTarget) // shared code doesn't depend on anything; all other targets depend only on the shared code
{
if (auto* sharedCodeTarget = owner.getTargetOfType (XcodeTarget::SharedCodeTarget))
dependencyIDs.add (sharedCodeTarget->addDependencyFor (*this));
}
}
//==============================================================================
void addTargetConfig (const String& configName, const StringArray& buildSettings)
{
auto configID = owner.createID (String ("targetconfigid_") + getName() + String ("_") + configName);
ValueTree v (configID);
v.setProperty ("isa", "XCBuildConfiguration", nullptr);
v.setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
v.setProperty (Ids::name, configName, nullptr);
configIDs.add (configID);
owner.addObject (v);
}
//==============================================================================
String getTargetAttributes() const
{
StringArray attributes;
auto developmentTeamID = owner.getDevelopmentTeamIDString();
if (developmentTeamID.isNotEmpty())
{
attributes.add ("DevelopmentTeam = " + developmentTeamID);
attributes.add ("ProvisioningStyle = Automatic");
}
std::map<String, bool> capabilities;
capabilities["ApplicationGroups.iOS"] = owner.iOS && owner.isAppGroupsEnabled();
capabilities["InAppPurchase"] = owner.isInAppPurchasesEnabled();
capabilities["InterAppAudio"] = owner.iOS && type == Target::StandalonePlugIn && owner.getProject().shouldEnableIAA();
capabilities["Push"] = owner.isPushNotificationsEnabled();
capabilities["Sandbox"] = type == Target::AudioUnitv3PlugIn || owner.isAppSandboxEnabled();
capabilities["HardenedRuntime"] = owner.isHardenedRuntimeEnabled();
if (owner.iOS && owner.isiCloudPermissionsEnabled())
capabilities["com.apple.iCloud"] = true;
StringArray capabilitiesStrings;
for (auto& capability : capabilities)
capabilitiesStrings.add ("com.apple." + capability.first + " = " + indentBracedList ({ String ("enabled = ") + (capability.second ? "1" : "0") }, 4));
attributes.add ("SystemCapabilities = " + indentBracedList (capabilitiesStrings, 3));
attributes.sort (false);
return getID() + " = " + indentBracedList (attributes, 2);
}
//==============================================================================
ValueTree addBuildPhase (const String& buildPhaseType, const StringArray& fileIds, const StringRef humanReadableName = StringRef())
{
auto buildPhaseName = buildPhaseType + "_" + getName() + "_" + (humanReadableName.isNotEmpty() ? String (humanReadableName) : String ("resbuildphase"));
auto buildPhaseId (owner.createID (buildPhaseName));
int n = 0;
while (buildPhaseIDs.contains (buildPhaseId))
buildPhaseId = owner.createID (buildPhaseName + String (++n));
buildPhaseIDs.add (buildPhaseId);
ValueTree v (buildPhaseId);
v.setProperty ("isa", buildPhaseType, nullptr);
v.setProperty ("buildActionMask", "2147483647", nullptr);
v.setProperty ("files", indentParenthesisedList (fileIds), nullptr);
if (humanReadableName.isNotEmpty())
v.setProperty ("name", String (humanReadableName), nullptr);
v.setProperty ("runOnlyForDeploymentPostprocessing", (int) 0, nullptr);
owner.addObject (v);
return v;
}
bool shouldCreatePList() const
{
auto fileType = getTargetFileType();
return (fileType == executable && type != ConsoleApp) || fileType == pluginBundle || fileType == macOSAppex;
}
//==============================================================================
bool shouldAddEntitlements() const
{
if (owner.isPushNotificationsEnabled()
|| owner.isAppGroupsEnabled()
|| owner.isAppSandboxEnabled()
|| owner.isHardenedRuntimeEnabled()
|| owner.isNetworkingMulticastEnabled()
|| (owner.isiOS() && owner.isiCloudPermissionsEnabled()))
return true;
if (owner.project.isAudioPluginProject()
&& ((owner.isOSX() && type == Target::AudioUnitv3PlugIn)
|| (owner.isiOS() && type == Target::StandalonePlugIn && owner.getProject().shouldEnableIAA())))
return true;
return false;
}
String getBundleIdentifier() const
{
auto exporterBundleIdentifier = owner.exporterBundleIdentifierValue.get().toString();
auto bundleIdentifier = exporterBundleIdentifier.isNotEmpty() ? exporterBundleIdentifier
: owner.project.getBundleIdentifierString();
if (xcodeBundleIDSubPath.isNotEmpty())
{
auto bundleIdSegments = StringArray::fromTokens (bundleIdentifier, ".", StringRef());
jassert (bundleIdSegments.size() > 0);
bundleIdentifier += String (".") + bundleIdSegments[bundleIdSegments.size() - 1] + xcodeBundleIDSubPath;
}
return bundleIdentifier;
}
StringPairArray getConfigPreprocessorDefs (const XcodeBuildConfiguration& config) const
{
StringPairArray defines;
if (config.isDebug())
{
defines.set ("_DEBUG", "1");
defines.set ("DEBUG", "1");
}
else
{
defines.set ("_NDEBUG", "1");
defines.set ("NDEBUG", "1");
}
if (owner.isInAppPurchasesEnabled())
defines.set ("JUCE_IN_APP_PURCHASES", "1");
if (owner.iOS && owner.isContentSharingEnabled())
defines.set ("JUCE_CONTENT_SHARING", "1");
if (owner.isPushNotificationsEnabled())
defines.set ("JUCE_PUSH_NOTIFICATIONS", "1");
return mergePreprocessorDefs (defines, owner.getAllPreprocessorDefs (config, type));
}
//==============================================================================
StringPairArray getTargetSettings (const XcodeBuildConfiguration& config) const
{
StringPairArray s;
if (type == AggregateTarget && ! owner.isiOS())
{
// the aggregate target needs to have the deployment target set for
// pre-/post-build scripts
s.set ("MACOSX_DEPLOYMENT_TARGET", config.getMacOSDeploymentTargetString());
s.set ("SDKROOT", "macosx" + config.getMacOSBaseSDKString());
return s;
}
s.set ("PRODUCT_NAME", owner.replacePreprocessorTokens (config, config.getTargetBinaryNameString (type == UnityPlugIn)).quoted());
s.set ("PRODUCT_BUNDLE_IDENTIFIER", getBundleIdentifier());
auto arch = (! owner.isiOS() && type == Target::AudioUnitv3PlugIn) ? macOSArch_64Bit
: config.getMacOSArchitectureString();
const auto archString = [&]() -> const char*
{
if (arch == macOSArch_Native) return "\"$(NATIVE_ARCH_ACTUAL)\"";
if (arch == macOSArch_32BitUniversal) return "\"$(ARCHS_STANDARD_32_BIT)\"";
if (arch == macOSArch_64BitUniversal) return "\"$(ARCHS_STANDARD_32_64_BIT)\"";
if (arch == macOSArch_64Bit) return "\"$(ARCHS_STANDARD_64_BIT)\"";
return nullptr;
}();
if (archString != nullptr)
s.set ("ARCHS", archString);
if (! owner.isiOS())
{
const auto validArchs = owner.getValidArchs();
if (! validArchs.isEmpty())
{
const auto join = [] (const Array<var>& range)
{
return std::accumulate (range.begin(),
range.end(),
String(),
[] (String str, const var& v) { return str + v.toString() + " "; }).trim().quoted();
};
s.set ("VALID_ARCHS", join (validArchs));
auto excludedArchs = owner.getAllArchs();
excludedArchs.removeIf ([&validArchs] (const auto& a) { return validArchs.contains (a); });
s.set ("EXCLUDED_ARCHS", join (excludedArchs));
}
}
auto headerPaths = getHeaderSearchPaths (config);
auto mtlHeaderPaths = headerPaths;
for (auto& path : mtlHeaderPaths)
path = path.unquoted();
s.set ("MTL_HEADER_SEARCH_PATHS", "\"" + mtlHeaderPaths.joinIntoString (" ") + "\"");
headerPaths.add ("\"$(inherited)\"");
s.set ("HEADER_SEARCH_PATHS", indentParenthesisedList (headerPaths, 1));
s.set ("USE_HEADERMAP", String (static_cast<bool> (config.exporter.settings.getProperty ("useHeaderMap")) ? "YES" : "NO"));
auto frameworksToSkip = [this]() -> String
{
const String openGLFramework (owner.iOS ? "OpenGLES" : "OpenGL");
if (owner.xcodeFrameworks.contains (openGLFramework))
return openGLFramework;
return {};
}();
if (frameworksToSkip.isNotEmpty())
s.set ("VALIDATE_WORKSPACE_SKIPPED_SDK_FRAMEWORKS", frameworksToSkip);
auto frameworkSearchPaths = getFrameworkSearchPaths (config);
if (! frameworkSearchPaths.isEmpty())
s.set ("FRAMEWORK_SEARCH_PATHS", String ("(") + frameworkSearchPaths.joinIntoString (", ") + ", \"$(inherited)\")");
s.set ("GCC_OPTIMIZATION_LEVEL", config.getGCCOptimisationFlag());
if (config.shouldUsePrecompiledHeaderFile())
{
s.set ("GCC_PRECOMPILE_PREFIX_HEADER", "YES");
auto pchFileContent = config.getPrecompiledHeaderFileContent();
if (pchFileContent.isNotEmpty())
{
auto pchFilename = config.getPrecompiledHeaderFilename() + ".h";
build_tools::writeStreamToFile (owner.getTargetFolder().getChildFile (pchFilename),
[&] (MemoryOutputStream& mo) { mo << pchFileContent; });
s.set ("GCC_PREFIX_HEADER", pchFilename);
}
}
if (shouldCreatePList())
{
s.set ("INFOPLIST_FILE", infoPlistFile.getFileName());
if (owner.getPListPrefixHeaderString().isNotEmpty())
s.set ("INFOPLIST_PREFIX_HEADER", owner.getPListPrefixHeaderString());
s.set ("INFOPLIST_PREPROCESS", (owner.isPListPreprocessEnabled() ? String ("YES") : String ("NO")));
auto plistDefs = parsePreprocessorDefs (config.getPListPreprocessorDefinitionsString());
StringArray defsList;
for (int i = 0; i < plistDefs.size(); ++i)
{
auto def = plistDefs.getAllKeys()[i];
auto value = plistDefs.getAllValues()[i];
if (value.isNotEmpty())
def << "=" << value.replace ("\"", "\\\\\\\"");
defsList.add ("\"" + def + "\"");
}
if (defsList.size() > 0)
s.set ("INFOPLIST_PREPROCESSOR_DEFINITIONS", indentParenthesisedList (defsList, 1));
}
if (config.isLinkTimeOptimisationEnabled())
s.set ("LLVM_LTO", "YES");
if (config.isFastMathEnabled())
s.set ("GCC_FAST_MATH", "YES");
auto recommendedWarnings = config.getRecommendedCompilerWarningFlags();
recommendedWarnings.cpp.addArray (recommendedWarnings.common);
struct XcodeWarningFlags
{
const StringArray& flags;
const String variable;
};
for (const auto& xcodeFlags : { XcodeWarningFlags { recommendedWarnings.common, "OTHER_CFLAGS" },
XcodeWarningFlags { recommendedWarnings.cpp, "OTHER_CPLUSPLUSFLAGS" } })
{
auto flags = (xcodeFlags.flags.joinIntoString (" ")
+ " " + owner.getExtraCompilerFlagsString()).trim();
flags = owner.replacePreprocessorTokens (config, flags);
if (flags.isNotEmpty())
s.set (xcodeFlags.variable, flags.quoted());
}
auto installPath = getInstallPathForConfiguration (config);
if (installPath.startsWith ("~"))
installPath = installPath.replace ("~", "$(HOME)");
if (installPath.isNotEmpty())
{
s.set ("INSTALL_PATH", installPath.quoted());
if (type == Target::SharedCodeTarget)
s.set ("SKIP_INSTALL", "YES");
if (! owner.embeddedFrameworkIDs.isEmpty())
s.set ("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks @executable_path/../Frameworks\"");
if (xcodeCopyToProductInstallPathAfterBuild)
{
s.set ("DEPLOYMENT_LOCATION", "YES");
s.set ("DSTROOT", "/");
}
}
if (getTargetFileType() == pluginBundle)
{
s.set ("LIBRARY_STYLE", "Bundle");
s.set ("WRAPPER_EXTENSION", xcodeBundleExtension.substring (1));
s.set ("GENERATE_PKGINFO_FILE", "YES");
}
if (xcodeOtherRezFlags.isNotEmpty())
s.set ("OTHER_REZFLAGS", "\"" + xcodeOtherRezFlags + "\"");
String configurationBuildDir ("$(PROJECT_DIR)/build/$(CONFIGURATION)");
if (config.getTargetBinaryRelativePathString().isNotEmpty())
{
// a target's position can either be defined via installPath + xcodeCopyToProductInstallPathAfterBuild
// (= for audio plug-ins) or using a custom binary path (for everything else), but not both (= conflict!)
jassert (! xcodeCopyToProductInstallPathAfterBuild);
build_tools::RelativePath binaryPath (config.getTargetBinaryRelativePathString(),
build_tools::RelativePath::projectFolder);
configurationBuildDir = expandPath (binaryPath.rebased (owner.projectFolder,
owner.getTargetFolder(),
build_tools::RelativePath::buildTargetFolder)
.toUnixStyle());
}
s.set ("CONFIGURATION_BUILD_DIR", addQuotesIfRequired (configurationBuildDir));
if (owner.isHardenedRuntimeEnabled())
s.set ("ENABLE_HARDENED_RUNTIME", "YES");
String gccVersion ("com.apple.compilers.llvm.clang.1_0");
if (owner.iOS)
{
s.set ("ASSETCATALOG_COMPILER_APPICON_NAME", "AppIcon");
if (! owner.shouldAddStoryboardToProject())
s.set ("ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME", "LaunchImage");
}
else
{
s.set ("MACOSX_DEPLOYMENT_TARGET", config.getMacOSDeploymentTargetString());
}
s.set ("GCC_VERSION", gccVersion);
s.set ("CLANG_LINK_OBJC_RUNTIME", "NO");
auto codeSigningIdentity = owner.getCodeSigningIdentity (config);
s.set (owner.iOS ? "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"" : "CODE_SIGN_IDENTITY",
codeSigningIdentity.quoted());
if (codeSigningIdentity.isNotEmpty())
{
s.set ("PROVISIONING_PROFILE_SPECIFIER", "\"\"");
if (! owner.isUsingDefaultSigningIdentity (config))
s.set ("CODE_SIGN_STYLE", "Manual");
}
if (owner.getDevelopmentTeamIDString().isNotEmpty())
s.set ("DEVELOPMENT_TEAM", owner.getDevelopmentTeamIDString());
if (shouldAddEntitlements())
s.set ("CODE_SIGN_ENTITLEMENTS", getEntitlementsFilename().quoted());
{
auto cppStandard = owner.project.getCppStandardString();
if (cppStandard == "latest")
cppStandard = owner.project.getLatestNumberedCppStandardString();
s.set ("CLANG_CXX_LANGUAGE_STANDARD", (String (owner.shouldUseGNUExtensions() ? "gnu++"
: "c++") + cppStandard).quoted());
}
s.set ("CLANG_CXX_LIBRARY", "\"libc++\"");
s.set ("COMBINE_HIDPI_IMAGES", "YES");
{
StringArray linkerFlags, librarySearchPaths;
getLinkerSettings (config, linkerFlags, librarySearchPaths);
if (linkerFlags.size() > 0)
s.set ("OTHER_LDFLAGS", linkerFlags.joinIntoString (" ").quoted());
librarySearchPaths.addArray (config.getLibrarySearchPaths());
librarySearchPaths = getCleanedStringArray (librarySearchPaths);
if (librarySearchPaths.size() > 0)
{
StringArray libPaths;
libPaths.add ("\"$(inherited)\"");
for (auto& p : librarySearchPaths)
libPaths.add ("\"\\\"" + p + "\\\"\"");
s.set ("LIBRARY_SEARCH_PATHS", indentParenthesisedList (libPaths, 1));
}
}
if (config.isDebug())
{
s.set ("COPY_PHASE_STRIP", "NO");
s.set ("GCC_DYNAMIC_NO_PIC", "NO");
}
else
{
s.set ("GCC_GENERATE_DEBUGGING_SYMBOLS", "NO");
s.set ("DEAD_CODE_STRIPPING", "YES");
}
if (type != Target::SharedCodeTarget && type != Target::StaticLibrary && type != Target::DynamicLibrary
&& config.isStripLocalSymbolsEnabled())
{
s.set ("STRIPFLAGS", "\"-x\"");
s.set ("DEPLOYMENT_POSTPROCESSING", "YES");
s.set ("SEPARATE_STRIP", "YES");
}
StringArray defsList;
const auto defines = getConfigPreprocessorDefs (config);
for (int i = 0; i < defines.size(); ++i)
{
auto def = defines.getAllKeys()[i];
auto value = defines.getAllValues()[i];
if (value.isNotEmpty())
def << "=" << value.replace ("\"", "\\\\\\\"").replace (" ", "\\\\ ").replace ("\'", "\\\\'");
defsList.add ("\"" + def + "\"");
}
s.set ("GCC_PREPROCESSOR_DEFINITIONS", indentParenthesisedList (defsList, 1));
StringArray customFlags;
customFlags.addTokens (config.getCustomXcodeFlagsString(), ",", "\"'");
customFlags.removeEmptyStrings();
for (auto flag : customFlags)
{
s.set (flag.upToFirstOccurrenceOf ("=", false, false).trim(),
flag.fromFirstOccurrenceOf ("=", false, false).trim().quoted());
}
return s;
}
String getInstallPathForConfiguration (const XcodeBuildConfiguration& config) const
{
switch (type)
{
case GUIApp: return "$(HOME)/Applications";
case ConsoleApp: return "/usr/bin";
case VSTPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getVSTBinaryLocationString() : String();
case VST3PlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getVST3BinaryLocationString() : String();
case AudioUnitPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getAUBinaryLocationString() : String();
case RTASPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getRTASBinaryLocationString() : String();
case AAXPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getAAXBinaryLocationString() : String();
case UnityPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getUnityPluginBinaryLocationString() : String();
case SharedCodeTarget: return owner.isiOS() ? "@executable_path/Frameworks" : "@executable_path/../Frameworks";
case StaticLibrary:
case DynamicLibrary:
case AudioUnitv3PlugIn:
case StandalonePlugIn:
case AggregateTarget:
case unspecified:
default: return {};
}
}
//==============================================================================
void getLinkerSettings (const BuildConfiguration& config, StringArray& flags, StringArray& librarySearchPaths) const
{
if (getTargetFileType() == pluginBundle)
flags.add (owner.isiOS() ? "-bitcode_bundle" : "-bundle");
if (type != Target::SharedCodeTarget)
{
Array<build_tools::RelativePath> extraLibs;
addExtraLibsForTargetType (config, extraLibs);
for (auto& lib : extraLibs)
{
flags.add (getLinkerFlagForLib (lib.getFileNameWithoutExtension()));
librarySearchPaths.add (owner.getSearchPathForStaticLibrary (lib));
}
if (owner.project.isAudioPluginProject())
{
if (owner.getTargetOfType (Target::SharedCodeTarget) != nullptr)
{
auto productName = getStaticLibbedFilename (owner.replacePreprocessorTokens (config, config.getTargetBinaryNameString()));
build_tools::RelativePath sharedCodelib (productName, build_tools::RelativePath::buildTargetFolder);
flags.add (getLinkerFlagForLib (sharedCodelib.getFileNameWithoutExtension()));
}
}
flags.add (owner.getExternalLibraryFlags (config));
auto libs = owner.xcodeLibs;
libs.addArray (xcodeLibs);
for (auto& l : libs)
flags.add (getLinkerFlagForLib (l));
}
flags.add (owner.replacePreprocessorTokens (config, owner.getExtraLinkerFlagsString()));
flags = getCleanedStringArray (flags);
}
//==========================================================================
void writeInfoPlistFile() const
{
if (! shouldCreatePList())
return;
build_tools::PlistOptions options;
options.type = type;
options.executableName = "${EXECUTABLE_NAME}";
options.bundleIdentifier = getBundleIdentifier();
options.applicationCategory = owner.getApplicationCategoryString();
options.plistToMerge = owner.getPListToMergeString();
options.iOS = owner.iOS;
options.microphonePermissionEnabled = owner.isMicrophonePermissionEnabled();
options.microphonePermissionText = owner.getMicrophonePermissionsTextString();
options.cameraPermissionEnabled = owner.isCameraPermissionEnabled();
options.cameraPermissionText = owner.getCameraPermissionTextString();
options.bluetoothPermissionEnabled = owner.isBluetoothPermissionEnabled();
options.bluetoothPermissionText = owner.getBluetoothPermissionTextString();
options.sendAppleEventsPermissionEnabled = owner.isSendAppleEventsPermissionEnabled();
options.sendAppleEventsPermissionText = owner.getSendAppleEventsPermissionTextString();
options.shouldAddStoryboardToProject = owner.shouldAddStoryboardToProject();
options.iconFile = owner.iconFile;
options.projectName = owner.projectName;
options.marketingVersion = owner.project.getVersionString();
options.currentProjectVersion = owner.getBuildNumber();
options.companyCopyright = owner.project.getCompanyCopyrightString();
options.allPreprocessorDefs = owner.getAllPreprocessorDefs();
options.documentExtensions = owner.getDocumentExtensionsString();
options.fileSharingEnabled = owner.isFileSharingEnabled();
options.documentBrowserEnabled = owner.isDocumentBrowserEnabled();
options.statusBarHidden = owner.isStatusBarHidden();
options.requiresFullScreen = owner.requiresFullScreen();
options.backgroundAudioEnabled = owner.isBackgroundAudioEnabled();
options.backgroundBleEnabled = owner.isBackgroundBleEnabled();
options.pushNotificationsEnabled = owner.isPushNotificationsEnabled();
options.enableIAA = owner.project.shouldEnableIAA();
options.IAAPluginName = owner.project.getIAAPluginName();
options.pluginManufacturerCode = owner.project.getPluginManufacturerCodeString();
options.IAATypeCode = owner.project.getIAATypeCode();
options.pluginCode = owner.project.getPluginCodeString();
options.iPhoneScreenOrientations = owner.getiPhoneScreenOrientations();
options.iPadScreenOrientations = owner.getiPadScreenOrientations();
options.storyboardName = [&]
{
const auto customLaunchStoryboard = owner.getCustomLaunchStoryboardString();
if (customLaunchStoryboard.isEmpty())
return owner.getDefaultLaunchStoryboardName();
return customLaunchStoryboard.fromLastOccurrenceOf ("/", false, false)
.upToLastOccurrenceOf (".storyboard", false, false);
}();
options.pluginName = owner.project.getPluginNameString();
options.pluginManufacturer = owner.project.getPluginManufacturerString();
options.pluginDescription = owner.project.getPluginDescriptionString();
options.pluginAUExportPrefix = owner.project.getPluginAUExportPrefixString();
options.auMainType = owner.project.getAUMainTypeString();
options.isAuSandboxSafe = owner.project.isAUSandBoxSafe();
options.isPluginSynth = owner.project.isPluginSynth();
options.suppressResourceUsage = owner.getSuppressPlistResourceUsage();
options.write (infoPlistFile);
}
//==============================================================================
void addShellScriptBuildPhase (const String& phaseName, const String& script)
{
if (script.trim().isNotEmpty())
{
auto v = addBuildPhase ("PBXShellScriptBuildPhase", {});
v.setProperty (Ids::name, phaseName, nullptr);
v.setProperty ("alwaysOutOfDate", 1, nullptr);
v.setProperty ("shellPath", "/bin/sh", nullptr);
v.setProperty ("shellScript", script.replace ("\\", "\\\\")
.replace ("\"", "\\\"")
.replace ("\r\n", "\\n")
.replace ("\n", "\\n"), nullptr);
}
}
void addCopyFilesPhase (const String& phaseName, const StringArray& files, XcodeCopyFilesDestinationIDs dst)
{
auto v = addBuildPhase ("PBXCopyFilesBuildPhase", files, phaseName);
v.setProperty ("dstPath", "", nullptr);
v.setProperty ("dstSubfolderSpec", (int) dst, nullptr);
}
//==============================================================================
void sanitiseAndEscapeSearchPaths (const BuildConfiguration& config, StringArray& paths) const
{
paths = getCleanedStringArray (paths);
for (auto& path : paths)
{
path = owner.replacePreprocessorTokens (config, expandPath (path));
if (path.containsChar (' '))
path = "\"\\\"" + path + "\\\"\""; // crazy double quotes required when there are spaces..
else
path = "\"" + path + "\"";
}
}
StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
{
StringArray paths (owner.extraSearchPaths);
paths.addArray (config.getHeaderSearchPaths());
paths.addArray (getTargetExtraHeaderSearchPaths());
if (owner.project.getEnabledModules().isModuleEnabled ("juce_audio_plugin_client"))
{
// Needed to compile .r files
paths.add (owner.getModuleFolderRelativeToProject ("juce_audio_plugin_client")
.rebased (owner.projectFolder, owner.getTargetFolder(), build_tools::RelativePath::buildTargetFolder)
.toUnixStyle());
}
sanitiseAndEscapeSearchPaths (config, paths);
return paths;
}
StringArray getFrameworkSearchPaths (const BuildConfiguration& config) const
{
auto paths = getSearchPathsFromString (owner.getFrameworkSearchPathsString());
sanitiseAndEscapeSearchPaths (config, paths);
return paths;
}
private:
//==============================================================================
void addExtraAudioUnitTargetSettings()
{
xcodeOtherRezFlags = "-d ppc_$ppc -d i386_$i386 -d ppc64_$ppc64 -d x86_64_$x86_64 -d arm64_$arm64"
" -I /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Versions/A/Headers"
" -I \\\"$(DEVELOPER_DIR)/Extras/CoreAudio/AudioUnits/AUPublic/AUBase\\\""
" -I \\\"$(DEVELOPER_DIR)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/AudioUnit.framework/Headers\\\"";
xcodeFrameworks.addArray ({ "AudioUnit", "CoreAudioKit" });
}
void addExtraAudioUnitv3PlugInTargetSettings()
{
xcodeFrameworks.addArray ({ "AVFoundation", "CoreAudioKit" });
if (owner.isOSX())
xcodeFrameworks.add ("AudioUnit");
}
void addExtraLibsForTargetType (const BuildConfiguration& config, Array<build_tools::RelativePath>& extraLibs) const
{
if (type == AAXPlugIn)
{
auto aaxLibsFolder = build_tools::RelativePath (owner.getAAXPathString(), build_tools::RelativePath::projectFolder).getChildFile ("Libs");
String libraryPath (config.isDebug() ? "Debug" : "Release");
libraryPath += "/libAAXLibrary_libcpp.a";
extraLibs.add (aaxLibsFolder.getChildFile (libraryPath));
}
else if (type == RTASPlugIn)
{
build_tools::RelativePath rtasFolder (owner.getRTASPathString(), build_tools::RelativePath::projectFolder);
extraLibs.add (rtasFolder.getChildFile ("MacBag/Libs/Debug/libPluginLibrary.a"));
extraLibs.add (rtasFolder.getChildFile ("MacBag/Libs/Release/libPluginLibrary.a"));
}
}
StringArray getTargetExtraHeaderSearchPaths() const
{
StringArray targetExtraSearchPaths;
if (type == RTASPlugIn)
{
build_tools::RelativePath rtasFolder (owner.getRTASPathString(), build_tools::RelativePath::projectFolder);
targetExtraSearchPaths.add ("$(DEVELOPER_DIR)/Headers/FlatCarbon");
targetExtraSearchPaths.add ("$(SDKROOT)/Developer/Headers/FlatCarbon");
static const char* p[] = { "AlturaPorts/TDMPlugIns/PlugInLibrary/Controls",
"AlturaPorts/TDMPlugIns/PlugInLibrary/CoreClasses",
"AlturaPorts/TDMPlugIns/PlugInLibrary/DSPClasses",
"AlturaPorts/TDMPlugIns/PlugInLibrary/EffectClasses",
"AlturaPorts/TDMPlugIns/PlugInLibrary/MacBuild",
"AlturaPorts/TDMPlugIns/PlugInLibrary/Meters",
"AlturaPorts/TDMPlugIns/PlugInLibrary/ProcessClasses",
"AlturaPorts/TDMPlugIns/PlugInLibrary/ProcessClasses/Interfaces",
"AlturaPorts/TDMPlugIns/PlugInLibrary/RTASP_Adapt",
"AlturaPorts/TDMPlugIns/PlugInLibrary/Utilities",
"AlturaPorts/TDMPlugIns/PlugInLibrary/ViewClasses",
"AlturaPorts/TDMPlugIns/DSPManager/**",
"AlturaPorts/TDMPlugIns/SupplementalPlugInLib/Encryption",
"AlturaPorts/TDMPlugIns/SupplementalPlugInLib/GraphicsExtensions",
"AlturaPorts/TDMPlugIns/common/**",
"AlturaPorts/TDMPlugIns/common/PI_LibInterface",
"AlturaPorts/TDMPlugIns/PACEProtection/**",
"AlturaPorts/TDMPlugIns/SignalProcessing/**",
"AlturaPorts/OMS/Headers",
"AlturaPorts/Fic/Interfaces/**",
"AlturaPorts/Fic/Source/SignalNets",
"AlturaPorts/DSIPublicInterface/PublicHeaders",
"DAEWin/Include",
"AlturaPorts/DigiPublic/Interfaces",
"AlturaPorts/DigiPublic",
"AlturaPorts/NewFileLibs/DOA",
"AlturaPorts/NewFileLibs/Cmn",
"xplat/AVX/avx2/avx2sdk/inc",
"xplat/AVX/avx2/avx2sdk/utils" };
for (auto* path : p)
owner.addProjectPathToBuildPathList (targetExtraSearchPaths, rtasFolder.getChildFile (path));
}
return targetExtraSearchPaths;
}
//==============================================================================
const XcodeProjectExporter& owner;
Target& operator= (const Target&) = delete;
};
mutable StringArray xcodeFrameworks;
StringArray xcodeLibs;
private:
//==============================================================================
static String expandPath (const String& path)
{
if (! build_tools::isAbsolutePath (path)) return "$(SRCROOT)/" + path;
if (path.startsWithChar ('~')) return "$(HOME)" + path.substring (1);
return path;
}
static String addQuotesIfRequired (const String& s)
{
return s.containsAnyOf (" $") ? s.quoted() : s;
}
File getProjectBundle() const { return getTargetFolder().getChildFile (project.getProjectFilenameRootString()).withFileExtension (".xcodeproj"); }
//==============================================================================
void createObjects() const
{
prepareTargets();
// Must be called before adding embedded frameworks, as we want to
// embed any frameworks found in subprojects.
addSubprojects();
addFrameworks();
addCustomResourceFolders();
addPlistFileReferences();
if (iOS && ! projectType.isStaticLibrary())
{
addXcassets();
if (shouldAddStoryboardToProject())
{
auto customLaunchStoryboard = getCustomLaunchStoryboardString();
if (customLaunchStoryboard.isEmpty())
writeDefaultLaunchStoryboardFile();
else if (getProject().getProjectFolder().getChildFile (customLaunchStoryboard).existsAsFile())
addLaunchStoryboardFileReference (build_tools::RelativePath (customLaunchStoryboard, build_tools::RelativePath::projectFolder)
.rebased (getProject().getProjectFolder(), getTargetFolder(), build_tools::RelativePath::buildTargetFolder));
}
}
else
{
addNibFiles();
}
addIcons();
addBuildConfigurations();
addProjectConfigList (createID ("__projList"));
{
StringArray topLevelGroupIDs;
addFilesAndGroupsToProject (topLevelGroupIDs);
addBuildPhases();
addExtraGroupsToProject (topLevelGroupIDs);
addGroup (createID ("__mainsourcegroup"), "Source", topLevelGroupIDs);
}
addProjectObject();
removeMismatchedXcuserdata();
}
void prepareTargets() const
{
for (auto* target : targets)
{
target->addDependencies();
if (target->type == XcodeTarget::AggregateTarget)
continue;
target->addMainBuildProduct();
auto targetName = String (target->getName());
auto fileID = createID (targetName + "__targetbuildref");
auto fileRefID = createID ("__productFileID" + targetName);
ValueTree v (fileID + " /* " + targetName + " */");
v.setProperty ("isa", "PBXBuildFile", nullptr);
v.setProperty ("fileRef", fileRefID, nullptr);
target->mainBuildProductID = fileID;
addObject (v);
}
}
void addPlistFileReferences() const
{
for (auto* target : targets)
{
if (target->type == XcodeTarget::AggregateTarget)
continue;
if (target->shouldCreatePList())
{
build_tools::RelativePath plistPath (target->infoPlistFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
addFileReference (plistPath.toUnixStyle());
resourceFileRefs.add (createFileRefID (plistPath));
}
}
}
void addNibFiles() const
{
build_tools::writeStreamToFile (menuNibFile, [&] (MemoryOutputStream& mo)
{
mo.write (BinaryData::RecentFilesMenuTemplate_nib, BinaryData::RecentFilesMenuTemplate_nibSize);
});
build_tools::RelativePath menuNibPath (menuNibFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
addFileReference (menuNibPath.toUnixStyle());
resourceIDs.add (addBuildFile (FileOptions().withRelativePath (menuNibPath)));
resourceFileRefs.add (createFileRefID (menuNibPath));
}
void addIcons() const
{
if (iconFile.exists())
{
build_tools::RelativePath iconPath (iconFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
addFileReference (iconPath.toUnixStyle());
resourceIDs.add (addBuildFile (FileOptions().withRelativePath (iconPath)));
resourceFileRefs.add (createFileRefID (iconPath));
}
}
void addBuildConfigurations() const
{
for (ConstConfigIterator config (*this); config.next();)
{
auto& xcodeConfig = dynamic_cast<const XcodeBuildConfiguration&> (*config);
StringArray settingsLines;
auto configSettings = getProjectSettings (xcodeConfig);
auto keys = configSettings.getAllKeys();
keys.sort (false);
for (auto& key : keys)
settingsLines.add (key + " = " + configSettings[key]);
addProjectConfig (config->getName(), settingsLines);
}
}
void addFilesAndGroupsToProject (StringArray& topLevelGroupIDs) const
{
for (auto* target : targets)
if (target->shouldAddEntitlements())
addEntitlementsFile (*target);
for (auto& group : getAllGroups())
{
if (group.getNumChildren() > 0)
{
auto groupID = addProjectItem (group);
if (groupID.isNotEmpty())
topLevelGroupIDs.add (groupID);
}
}
}
void addExtraGroupsToProject (StringArray& topLevelGroupIDs) const
{
{
auto resourcesGroupID = createID ("__resources");
addGroup (resourcesGroupID, "Resources", resourceFileRefs);
topLevelGroupIDs.add (resourcesGroupID);
}
{
auto frameworksGroupID = createID ("__frameworks");
addGroup (frameworksGroupID, "Frameworks", frameworkFileIDs);
topLevelGroupIDs.add (frameworksGroupID);
}
{
auto productsGroupID = createID ("__products");
addGroup (productsGroupID, "Products", buildProducts);
topLevelGroupIDs.add (productsGroupID);
}
if (! subprojectFileIDs.isEmpty())
{
auto subprojectLibrariesGroupID = createID ("__subprojects");
addGroup (subprojectLibrariesGroupID, "Subprojects", subprojectFileIDs);
topLevelGroupIDs.add (subprojectLibrariesGroupID);
}
}
void addBuildPhases() const
{
// add build phases
for (auto* target : targets)
{
if (target->type != XcodeTarget::AggregateTarget)
buildProducts.add (createID (String ("__productFileID") + String (target->getName())));
for (ConstConfigIterator config (*this); config.next();)
{
auto& xcodeConfig = dynamic_cast<const XcodeBuildConfiguration&> (*config);
auto configSettings = target->getTargetSettings (xcodeConfig);
StringArray settingsLines;
auto keys = configSettings.getAllKeys();
keys.sort (false);
for (auto& key : keys)
settingsLines.add (key + " = " + configSettings.getValue (key, "\"\""));
target->addTargetConfig (config->getName(), settingsLines);
}
addConfigList (*target, createID (String ("__configList") + target->getName()));
target->addShellScriptBuildPhase ("Pre-build script", getPreBuildScript());
if (target->type != XcodeTarget::AggregateTarget)
{
auto skipAUv3 = (target->type == XcodeTarget::AudioUnitv3PlugIn && ! shouldDuplicateAppExResourcesFolder());
if (! projectType.isStaticLibrary() && target->type != XcodeTarget::SharedCodeTarget && ! skipAUv3)
target->addBuildPhase ("PBXResourcesBuildPhase", resourceIDs);
auto rezFiles = rezFileIDs;
rezFiles.addArray (target->rezFileIDs);
if (rezFiles.size() > 0)
target->addBuildPhase ("PBXRezBuildPhase", rezFiles);
auto sourceFiles = target->sourceIDs;
if (target->type == XcodeTarget::SharedCodeTarget
|| (! project.isAudioPluginProject()))
sourceFiles.addArray (sourceIDs);
target->addBuildPhase ("PBXSourcesBuildPhase", sourceFiles);
if (! projectType.isStaticLibrary() && target->type != XcodeTarget::SharedCodeTarget)
target->addBuildPhase ("PBXFrameworksBuildPhase", target->frameworkIDs);
}
target->addShellScriptBuildPhase ("Post-build script", getPostBuildScript());
if (project.isAudioPluginProject() && project.shouldBuildAUv3()
&& project.shouldBuildStandalonePlugin() && target->type == XcodeTarget::StandalonePlugIn)
embedAppExtension();
if (project.isAudioPluginProject() && project.shouldBuildUnityPlugin()
&& target->type == XcodeTarget::UnityPlugIn)
embedUnityScript();
addTargetObject (*target);
}
}
void embedAppExtension() const
{
if (auto* standaloneTarget = getTargetOfType (XcodeTarget::StandalonePlugIn))
{
if (auto* auv3Target = getTargetOfType (XcodeTarget::AudioUnitv3PlugIn))
{
StringArray files;
files.add (auv3Target->mainBuildProductID);
standaloneTarget->addCopyFilesPhase ("Embed App Extensions", files, kPluginsFolder);
}
}
}
void embedUnityScript() const
{
if (auto* unityTarget = getTargetOfType (XcodeTarget::UnityPlugIn))
{
build_tools::RelativePath scriptPath (getProject().getGeneratedCodeFolder().getChildFile (getProject().getUnityScriptName()),
getTargetFolder(),
build_tools::RelativePath::buildTargetFolder);
auto path = scriptPath.toUnixStyle();
auto refID = addFileReference (path);
auto fileID = addBuildFile (FileOptions().withPath (path)
.withFileRefID (refID));
resourceIDs.add (fileID);
resourceFileRefs.add (refID);
unityTarget->addCopyFilesPhase ("Embed Unity Script", fileID, kResourcesFolder);
}
}
//==============================================================================
XcodeTarget* getTargetOfType (build_tools::ProjectType::Target::Type type) const
{
for (auto& target : targets)
if (target->type == type)
return target;
return nullptr;
}
void addTargetObject (XcodeTarget& target) const
{
auto targetName = target.getName();
auto targetID = target.getID();
ValueTree v (targetID);
v.setProperty ("isa", target.type == XcodeTarget::AggregateTarget ? "PBXAggregateTarget" : "PBXNativeTarget", nullptr);
v.setProperty ("buildConfigurationList", createID (String ("__configList") + targetName), nullptr);
v.setProperty ("buildPhases", indentParenthesisedList (target.buildPhaseIDs), nullptr);
if (target.type != XcodeTarget::AggregateTarget)
v.setProperty ("buildRules", indentParenthesisedList ({}), nullptr);
StringArray allDependencyIDs { subprojectDependencyIDs };
allDependencyIDs.addArray (target.dependencyIDs);
v.setProperty ("dependencies", indentParenthesisedList (allDependencyIDs), nullptr);
v.setProperty (Ids::name, target.getXcodeSchemeName(), nullptr);
v.setProperty ("productName", projectName, nullptr);
if (target.type != XcodeTarget::AggregateTarget)
{
v.setProperty ("productReference", createID (String ("__productFileID") + targetName), nullptr);
jassert (target.xcodeProductType.isNotEmpty());
v.setProperty ("productType", target.xcodeProductType, nullptr);
}
targetIDs.add (targetID);
addObject (v);
}
void createIconFile() const
{
const auto icons = getIcons();
if (! build_tools::asArray (icons).isEmpty())
{
iconFile = getTargetFolder().getChildFile ("Icon.icns");
build_tools::writeMacIcon (icons, iconFile);
}
}
void writeWorkspaceSettings() const
{
const auto settingsFile = getProjectBundle().getChildFile ("project.xcworkspace")
.getChildFile ("xcshareddata")
.getChildFile ("WorkspaceSettings.xcsettings");
if (shouldUseLegacyBuildSystem())
{
build_tools::writeStreamToFile (settingsFile, [this] (MemoryOutputStream& mo)
{
mo.setNewLineString (getNewLineString());
mo << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << newLine
<< "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << newLine
<< "<plist version=\"1.0\">" << newLine
<< "<dict>" << newLine
<< "\t" << "<key>BuildSystemType</key>" << newLine
<< "\t" << "<string>Original</string>" << newLine
<< "\t" << "<key>DisableBuildSystemDeprecationWarning</key>" << newLine
<< "\t" << "<true/>" << newLine
<< "\t" << "<key>DisableBuildSystemDeprecationDiagnostic</key>" << newLine
<< "\t" << "<true/>" << newLine
<< "</dict>" << newLine
<< "</plist>" << newLine;
});
}
else
{
settingsFile.deleteFile();
}
}
void writeInfoPlistFiles() const
{
for (auto& target : targets)
target->writeInfoPlistFile();
}
// Delete .rsrc files in folder but don't follow sym-links
void deleteRsrcFiles (const File& folder) const
{
for (const auto& di : RangedDirectoryIterator (folder, false, "*", File::findFilesAndDirectories))
{
const auto& entry = di.getFile();
if (! entry.isSymbolicLink())
{
if (entry.existsAsFile() && entry.getFileExtension().toLowerCase() == ".rsrc")
entry.deleteFile();
else if (entry.isDirectory())
deleteRsrcFiles (entry);
}
}
}
static String getLinkerFlagForLib (String library)
{
if (library.substring (0, 3) == "lib")
library = library.substring (3);
return "-l" + library.replace (" ", "\\\\ ").replace ("\"", "\\\\\"").replace ("\'", "\\\\\'").upToLastOccurrenceOf (".", false, false);
}
String getSearchPathForStaticLibrary (const build_tools::RelativePath& library) const
{
auto searchPath = library.toUnixStyle().upToLastOccurrenceOf ("/", false, false);
if (! library.isAbsolute())
{
auto srcRoot = rebaseFromProjectFolderToBuildTarget (build_tools::RelativePath (".", build_tools::RelativePath::projectFolder)).toUnixStyle();
if (srcRoot.endsWith ("/.")) srcRoot = srcRoot.dropLastCharacters (2);
if (! srcRoot.endsWithChar ('/')) srcRoot << '/';
searchPath = srcRoot + searchPath;
}
return expandPath (searchPath);
}
bool isUsingDefaultSigningIdentity (const XcodeBuildConfiguration& config) const
{
return config.getCodeSignIdentityString().isEmpty() && getDevelopmentTeamIDString().isNotEmpty();
}
String getCodeSigningIdentity (const XcodeBuildConfiguration& config) const
{
if (isUsingDefaultSigningIdentity (config))
return iOS ? "iPhone Developer" : "Mac Developer";
const auto identity = config.getCodeSignIdentityString();
return identity.isNotEmpty() ? identity : "-";
}
StringPairArray getProjectSettings (const XcodeBuildConfiguration& config) const
{
StringPairArray s;
s.set ("ALWAYS_SEARCH_USER_PATHS", "NO");
s.set ("ENABLE_STRICT_OBJC_MSGSEND", "YES");
s.set ("GCC_C_LANGUAGE_STANDARD", "c11");
s.set ("GCC_NO_COMMON_BLOCKS", "YES");
s.set ("GCC_MODEL_TUNING", "G5");
s.set ("GCC_WARN_ABOUT_RETURN_TYPE", "YES");
s.set ("GCC_WARN_CHECK_SWITCH_STATEMENTS", "YES");
s.set ("GCC_WARN_UNUSED_VARIABLE", "YES");
s.set ("GCC_WARN_MISSING_PARENTHESES", "YES");
s.set ("GCC_WARN_NON_VIRTUAL_DESTRUCTOR", "YES");
s.set ("GCC_WARN_TYPECHECK_CALLS_TO_PRINTF", "YES");
s.set ("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES");
s.set ("GCC_WARN_UNDECLARED_SELECTOR", "YES");
s.set ("GCC_WARN_UNINITIALIZED_AUTOS", "YES");
s.set ("GCC_WARN_UNUSED_FUNCTION", "YES");
s.set ("CLANG_ENABLE_OBJC_WEAK", "YES");
s.set ("CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING", "YES");
s.set ("CLANG_WARN_BOOL_CONVERSION", "YES");
s.set ("CLANG_WARN_COMMA", "YES");
s.set ("CLANG_WARN_CONSTANT_CONVERSION", "YES");
s.set ("CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS", "YES");
s.set ("CLANG_WARN_EMPTY_BODY", "YES");
s.set ("CLANG_WARN_ENUM_CONVERSION", "YES");
s.set ("CLANG_WARN_INFINITE_RECURSION", "YES");
s.set ("CLANG_WARN_INT_CONVERSION", "YES");
s.set ("CLANG_WARN_NON_LITERAL_NULL_CONVERSION", "YES");
s.set ("CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF", "YES");
s.set ("CLANG_WARN_OBJC_LITERAL_CONVERSION", "YES");
s.set ("CLANG_WARN_RANGE_LOOP_ANALYSIS", "YES");
s.set ("CLANG_WARN_STRICT_PROTOTYPES", "YES");
s.set ("CLANG_WARN_SUSPICIOUS_MOVE", "YES");
s.set ("CLANG_WARN_UNREACHABLE_CODE", "YES");
s.set ("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES");
s.set ("WARNING_CFLAGS", "\"-Wreorder\"");
s.set ("GCC_INLINES_ARE_PRIVATE_EXTERN", projectType.isStaticLibrary() ? "NO" : "YES");
// GCC_SYMBOLS_PRIVATE_EXTERN only takes effect if ENABLE_TESTABILITY is off
s.set ("ENABLE_TESTABILITY", "NO");
s.set ("GCC_SYMBOLS_PRIVATE_EXTERN", "YES");
if (config.isDebug())
{
if (config.getMacOSArchitectureString() == macOSArch_Default)
s.set ("ONLY_ACTIVE_ARCH", "YES");
}
s.set (iOS ? "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"" : "CODE_SIGN_IDENTITY",
getCodeSigningIdentity (config).quoted());
if (iOS)
{
s.set ("SDKROOT", "iphoneos" + config.getiOSBaseSDKString());
s.set ("TARGETED_DEVICE_FAMILY", getDeviceFamilyString().quoted());
s.set ("IPHONEOS_DEPLOYMENT_TARGET", config.getiOSDeploymentTargetString());
}
else
{
s.set ("SDKROOT", "macosx" + config.getMacOSBaseSDKString());
}
s.set ("ZERO_LINK", "NO");
if (xcodeCanUseDwarf)
s.set ("DEBUG_INFORMATION_FORMAT", "dwarf");
s.set ("PRODUCT_NAME", replacePreprocessorTokens (config, config.getTargetBinaryNameString()).quoted());
return s;
}
template<typename AddFrameworkFn>
void addFrameworkList (const String& frameworksString, AddFrameworkFn&& addFrameworkFn) const
{
auto frameworks = StringArray::fromTokens (frameworksString, "\n\r", "\"'");
frameworks.trim();
for (auto& framework : frameworks)
{
auto frameworkID = addFrameworkFn (framework);
for (auto& target : targets)
{
target->frameworkIDs.add (frameworkID);
target->frameworkNames.add (framework);
}
}
}
void addFrameworks() const
{
if (! projectType.isStaticLibrary())
{
if (isInAppPurchasesEnabled())
xcodeFrameworks.addIfNotAlreadyThere ("StoreKit");
if (iOS)
{
if (isPushNotificationsEnabled())
xcodeFrameworks.addIfNotAlreadyThere ("UserNotifications");
if (project.getEnabledModules().isModuleEnabled ("juce_video")
&& project.isConfigFlagEnabled ("JUCE_USE_CAMERA", false))
{
xcodeFrameworks.addIfNotAlreadyThere ("ImageIO");
}
}
xcodeFrameworks.addTokens (getExtraFrameworksString(), ",;", "\"'");
xcodeFrameworks.trim();
auto s = xcodeFrameworks;
for (auto& target : targets)
s.addArray (target->xcodeFrameworks);
if (! project.getConfigFlag ("JUCE_QUICKTIME").get())
s.removeString ("QuickTime");
s.trim();
s.removeDuplicates (true);
s.sort (true);
// When building against the 10.15 SDK we need to make sure the
// AudioUnit framework is linked before the AudioToolbox framework.
auto audioUnitIndex = s.indexOf ("AudioUnit", false, 1);
if (audioUnitIndex != -1)
{
s.remove (audioUnitIndex);
s.insert (0, "AudioUnit");
}
for (auto& framework : s)
{
auto frameworkID = addFramework (framework);
// find all the targets that are referring to this object
for (auto& target : targets)
{
if (xcodeFrameworks.contains (framework) || target->xcodeFrameworks.contains (framework))
{
target->frameworkIDs.add (frameworkID);
target->frameworkNames.add (framework);
}
}
}
}
addFrameworkList (getExtraCustomFrameworksString(),
[this] (const String& framework) { return addCustomFramework (framework); });
addFrameworkList (getEmbeddedFrameworksString(),
[this] (const String& framework)
{
auto frameworkId = addEmbeddedFramework (framework);
embeddedFrameworkIDs.add (frameworkId);
return frameworkId;
});
if (! embeddedFrameworkIDs.isEmpty())
for (auto& target : targets)
target->addCopyFilesPhase ("Embed Frameworks", embeddedFrameworkIDs, kFrameworksFolder);
}
void addCustomResourceFolders() const
{
StringArray folders;
folders.addTokens (getCustomResourceFoldersString(), ":", "");
folders.trim();
folders.removeEmptyStrings();
for (auto& crf : folders)
addCustomResourceFolder (crf);
}
void addSubprojects() const
{
auto subprojectLines = StringArray::fromLines (getSubprojectsString());
subprojectLines.removeEmptyStrings (true);
struct SubprojectInfo
{
String path;
StringArray buildProducts;
};
std::vector<SubprojectInfo> subprojects;
for (auto& line : subprojectLines)
{
String subprojectPath (line.upToFirstOccurrenceOf (":", false, false));
if (! subprojectPath.endsWith (".xcodeproj"))
subprojectPath << ".xcodeproj";
StringArray requestedBuildProducts (StringArray::fromTokens (line.fromFirstOccurrenceOf (":", false, false), ",;|", "\"'"));
requestedBuildProducts.trim();
subprojects.push_back ({ subprojectPath, requestedBuildProducts });
}
for (const auto& subprojectInfo : subprojects)
{
auto subprojectFile = getTargetFolder().getChildFile (subprojectInfo.path);
if (! subprojectFile.isDirectory())
continue;
auto availableBuildProducts = XcodeProjectParser::parseBuildProducts (subprojectFile);
if (! subprojectInfo.buildProducts.isEmpty())
{
auto newEnd = std::remove_if (availableBuildProducts.begin(), availableBuildProducts.end(),
[&subprojectInfo] (const XcodeProjectParser::BuildProduct& item)
{
return ! subprojectInfo.buildProducts.contains (item.name);
});
availableBuildProducts.erase (newEnd, availableBuildProducts.end());
}
if (availableBuildProducts.empty())
continue;
auto subprojectPath = build_tools::RelativePath (subprojectFile,
getTargetFolder(),
build_tools::RelativePath::buildTargetFolder).toUnixStyle();
auto subprojectFileType = getFileType (subprojectPath);
auto subprojectFileID = addFileOrFolderReference (subprojectPath, "<group>", subprojectFileType);
subprojectFileIDs.add (subprojectFileID);
StringArray productIDs;
for (auto& buildProduct : availableBuildProducts)
{
auto buildProductFileType = getFileType (buildProduct.path);
auto dependencyProxyID = addContainerItemProxy (subprojectFileID, buildProduct.name, "1");
auto dependencyID = addTargetDependency (dependencyProxyID, buildProduct.name);
subprojectDependencyIDs.add (dependencyID);
auto containerItemProxyReferenceID = addContainerItemProxy (subprojectFileID, buildProduct.name, "2");
auto proxyID = addReferenceProxy (containerItemProxyReferenceID, buildProduct.path, buildProductFileType);
productIDs.add (proxyID);
if (StringArray { "archive.ar", "compiled.mach-o.dylib", "wrapper.framework" }.contains (buildProductFileType))
{
auto buildFileID = addBuildFile (FileOptions().withPath (buildProduct.path)
.withFileRefID (proxyID)
.withInhibitWarningsEnabled (true));
for (auto& target : targets)
target->frameworkIDs.add (buildFileID);
if (buildProductFileType == "wrapper.framework")
{
auto fileID = createID (subprojectPath + "_" + buildProduct.path + "_framework_buildref");
ValueTree v (fileID + " /* " + buildProduct.path + " */");
v.setProperty ("isa", "PBXBuildFile", nullptr);
v.setProperty ("fileRef", proxyID, nullptr);
v.setProperty ("settings", "{ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }", nullptr);
addObject (v);
embeddedFrameworkIDs.add (fileID);
}
}
}
auto productGroupID = createFileRefID (subprojectFile.getFullPathName() + "_products");
addGroup (productGroupID, "Products", productIDs);
subprojectReferences.add ({ productGroupID, subprojectFileID });
}
}
void addXcassets() const
{
auto customXcassetsPath = getCustomXcassetsFolderString();
if (customXcassetsPath.isEmpty())
addDefaultXcassetsFolders();
else
addCustomResourceFolder (customXcassetsPath, "folder.assetcatalog");
}
void addCustomResourceFolder (String folderPathRelativeToProjectFolder, const String fileType = "folder") const
{
auto folderPath = build_tools::RelativePath (folderPathRelativeToProjectFolder, build_tools::RelativePath::projectFolder)
.rebased (projectFolder, getTargetFolder(), build_tools::RelativePath::buildTargetFolder)
.toUnixStyle();
auto fileRefID = createFileRefID (folderPath);
addFileOrFolderReference (folderPath, "<group>", fileType);
resourceIDs.add (addBuildFile (FileOptions().withPath (folderPath)
.withFileRefID (fileRefID)));
resourceFileRefs.add (createFileRefID (folderPath));
}
//==============================================================================
void writeProjectFile (OutputStream& output) const
{
output << "// !$*UTF8*$!\n{\n"
"\tarchiveVersion = 1;\n"
"\tclasses = {\n\t};\n"
"\tobjectVersion = 46;\n"
"\tobjects = {\n";
StringArray objectTypes;
for (auto it : objects)
objectTypes.add (it.getType().toString());
objectTypes.sort (false);
for (const auto& objectType : objectTypes)
{
auto objectsWithType = objects.getChildWithName (objectType);
auto requiresSingleLine = objectType == "PBXBuildFile" || objectType == "PBXFileReference";
output << "\n/* Begin " << objectType << " section */\n";
for (const auto& o : objectsWithType)
{
auto label = [&o]() -> String
{
if (auto* objName = o.getPropertyPointer ("name"))
return " /* " + objName->toString() + " */";
return {};
}();
output << "\t\t" << o.getType().toString() << label << " = {";
if (! requiresSingleLine)
output << "\n";
for (int j = 0; j < o.getNumProperties(); ++j)
{
auto propertyName = o.getPropertyName (j);
auto val = o.getProperty (propertyName).toString();
if (val.isEmpty() || (val.containsAnyOf (" \t;<>()=,&+-@~\r\n\\#%^`*")
&& ! (val.trimStart().startsWithChar ('(')
|| val.trimStart().startsWithChar ('{'))))
val = "\"" + val + "\"";
auto content = propertyName.toString() + " = " + val + ";";
if (requiresSingleLine)
content = content + " ";
else
content = "\t\t\t" + content + "\n";
output << content;
}
if (! requiresSingleLine)
output << "\t\t";
output << "};\n";
}
output << "/* End " << objectType << " section */\n";
}
output << "\t};\n\trootObject = " << createID ("__root") << " /* Project object */;\n}\n";
}
String addFileReference (String pathString, String fileType = {}) const
{
String sourceTree ("SOURCE_ROOT");
build_tools::RelativePath path (pathString, build_tools::RelativePath::unknown);
if (pathString.startsWith ("${"))
{
sourceTree = pathString.substring (2).upToFirstOccurrenceOf ("}", false, false);
pathString = pathString.fromFirstOccurrenceOf ("}/", false, false);
}
else if (path.isAbsolute())
{
sourceTree = "<absolute>";
}
return addFileOrFolderReference (pathString, sourceTree, fileType.isEmpty() ? getFileType (pathString) : fileType);
}
String addFileOrFolderReference (const String& pathString, String sourceTree, String fileType) const
{
auto fileRefID = createFileRefID (pathString);
auto filename = build_tools::RelativePath (pathString, build_tools::RelativePath::unknown).getFileName();
ValueTree v (fileRefID + " /* " + filename + " */");
v.setProperty ("isa", "PBXFileReference", nullptr);
v.setProperty ("lastKnownFileType", fileType, nullptr);
v.setProperty (Ids::name, pathString.fromLastOccurrenceOf ("/", false, false), nullptr);
v.setProperty ("path", pathString, nullptr);
v.setProperty ("sourceTree", sourceTree, nullptr);
addObject (v);
return fileRefID;
}
String addContainerItemProxy (const String& subprojectID, const String& itemName, const String& proxyType) const
{
auto uniqueString = subprojectID + "_" + itemName + "_" + proxyType;
auto objectID = createFileRefID (uniqueString);
ValueTree v (objectID + " /* PBXContainerItemProxy */");
v.setProperty ("isa", "PBXContainerItemProxy", nullptr);
v.setProperty ("containerPortal", subprojectID, nullptr);
v.setProperty ("proxyType", proxyType, nullptr);
v.setProperty ("remoteGlobalIDString", createFileRefID (uniqueString + "_global"), nullptr);
v.setProperty ("remoteInfo", itemName, nullptr);
addObject (v);
return objectID;
}
String addTargetDependency (const String& proxyID, const String& itemName) const
{
auto objectID = createFileRefID (proxyID + "_" + itemName + "_PBXTargetDependency");
ValueTree v (objectID);
v.setProperty ("isa", "PBXTargetDependency", nullptr);
v.setProperty ("name", itemName, nullptr);
v.setProperty ("targetProxy", proxyID, nullptr);
addObject (v);
return objectID;
}
String addReferenceProxy (const String& remoteRef, const String& path, const String& fileType) const
{
auto objectID = createFileRefID (remoteRef + "_" + path);
ValueTree v (objectID + " /* " + path + " */");
v.setProperty ("isa", "PBXReferenceProxy", nullptr);
v.setProperty ("fileType", fileType, nullptr);
v.setProperty ("path", path, nullptr);
v.setProperty ("remoteRef", remoteRef, nullptr);
v.setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);
addObject (v);
return objectID;
}
private:
struct FileOptions
{
FileOptions& withPath (const String& p) { path = p; return *this; }
FileOptions& withRelativePath (const build_tools::RelativePath& p) { path = p.toUnixStyle(); return *this; }
FileOptions& withFileRefID (const String& fid) { fileRefID = fid; return *this; }
FileOptions& withCompilerFlags (const String& f) { compilerFlags = f; return *this; }
FileOptions& withCompilationEnabled (bool e) { compile = e; return *this; }
FileOptions& withAddToBinaryResourcesEnabled (bool e) { addToBinaryResources = e; return *this; }
FileOptions& withAddToXcodeResourcesEnabled (bool e) { addToXcodeResources = e; return *this; }
FileOptions& withInhibitWarningsEnabled (bool e) { inhibitWarnings = e; return *this; }
FileOptions& withSkipPCHEnabled (bool e) { skipPCH = e; return *this; }
FileOptions& withXcodeTarget (XcodeTarget* t) { xcodeTarget = t; return *this; }
String path;
String fileRefID;
String compilerFlags;
bool compile = false;
bool addToBinaryResources = false;
bool addToXcodeResources = false;
bool inhibitWarnings = false;
bool skipPCH = false;
XcodeTarget* xcodeTarget = nullptr;
};
static String getFileType (const String& filePath)
{
build_tools::RelativePath file (filePath, build_tools::RelativePath::unknown);
if (file.hasFileExtension (cppFileExtensions)) return "sourcecode.cpp.cpp";
if (file.hasFileExtension (".mm")) return "sourcecode.cpp.objcpp";
if (file.hasFileExtension (".m")) return "sourcecode.c.objc";
if (file.hasFileExtension (".c")) return "sourcecode.c.c";
if (file.hasFileExtension (headerFileExtensions)) return "sourcecode.c.h";
if (file.hasFileExtension (asmFileExtensions)) return "sourcecode.c.asm";
if (file.hasFileExtension (".framework")) return "wrapper.framework";
if (file.hasFileExtension (".jpeg;.jpg")) return "image.jpeg";
if (file.hasFileExtension ("png;gif")) return "image" + file.getFileExtension();
if (file.hasFileExtension ("html;htm")) return "text.html";
if (file.hasFileExtension ("xml;zip;wav")) return "file" + file.getFileExtension();
if (file.hasFileExtension ("txt;rtf")) return "text" + file.getFileExtension();
if (file.hasFileExtension ("plist")) return "text.plist.xml";
if (file.hasFileExtension ("entitlements")) return "text.plist.xml";
if (file.hasFileExtension ("app")) return "wrapper.application";
if (file.hasFileExtension ("component;vst;plugin")) return "wrapper.cfbundle";
if (file.hasFileExtension ("xcodeproj")) return "wrapper.pb-project";
if (file.hasFileExtension ("a")) return "archive.ar";
if (file.hasFileExtension ("dylib")) return "compiled.mach-o.dylib";
if (file.hasFileExtension ("xcassets")) return "folder.assetcatalog";
return "file" + file.getFileExtension();
}
String addFile (const FileOptions& opts) const
{
auto refID = addFileReference (opts.path);
if (opts.compile || opts.addToXcodeResources)
{
auto fileID = addBuildFile (FileOptions (opts).withFileRefID (refID));
if (opts.addToXcodeResources)
{
resourceIDs.add (fileID);
resourceFileRefs.add (refID);
}
}
return refID;
}
String addBuildFile (const FileOptions& opts) const
{
auto fileID = createID (opts.path + "buildref");
auto filename = build_tools::RelativePath (opts.path, build_tools::RelativePath::unknown).getFileName();
if (opts.compile)
{
if (opts.xcodeTarget != nullptr)
opts.xcodeTarget->sourceIDs.add (fileID);
else
sourceIDs.add (fileID);
}
ValueTree v (fileID + " /* " + filename + " */");
v.setProperty ("isa", "PBXBuildFile", nullptr);
auto fileRefID = opts.fileRefID.isEmpty() ? createFileRefID (opts.path)
: opts.fileRefID;
v.setProperty ("fileRef", fileRefID, nullptr);
auto compilerFlags = [&opts]
{
return (opts.compilerFlags
+ (opts.inhibitWarnings ? " -w" : String())
+ (opts.skipPCH ? " -D" + BuildConfiguration::getSkipPrecompiledHeaderDefine() : String())).trim();
}();
if (compilerFlags.isNotEmpty())
v.setProperty ("settings", "{ COMPILER_FLAGS = \"" + compilerFlags + "\"; }", nullptr);
addObject (v);
return fileID;
}
String addRezFile (const Project::Item& projectItem, const build_tools::RelativePath& path) const
{
auto refID = addFileReference (path.toUnixStyle());
if (projectItem.isModuleCode())
{
if (auto* xcodeTarget = getTargetOfType (getProject().getTargetTypeFromFilePath (projectItem.getFile(), false)))
{
auto rezFileID = addBuildFile (FileOptions().withRelativePath (path)
.withFileRefID (refID)
.withXcodeTarget (xcodeTarget));
xcodeTarget->rezFileIDs.add (rezFileID);
return refID;
}
}
return {};
}
void addEntitlementsFile (XcodeTarget& target) const
{
build_tools::EntitlementOptions options;
options.type = target.type;
options.isiOS = isiOS();
options.isAudioPluginProject = project.isAudioPluginProject();
options.shouldEnableIAA = project.shouldEnableIAA();
options.isiCloudPermissionsEnabled = isiCloudPermissionsEnabled();
options.isPushNotificationsEnabled = isPushNotificationsEnabled();
options.isAppGroupsEnabled = isAppGroupsEnabled();
options.isHardenedRuntimeEnabled = isHardenedRuntimeEnabled();
options.isAppSandboxEnabled = isAppSandboxEnabled();
options.isAppSandboxInhertianceEnabled = isAppSandboxInhertianceEnabled();
options.isNetworkingMulticastEnabled = isNetworkingMulticastEnabled();
options.appGroupIdString = getAppGroupIdString();
options.hardenedRuntimeOptions = getHardenedRuntimeOptions();
options.appSandboxOptions = getAppSandboxOptions();
const auto entitlementsFile = getTargetFolder().getChildFile (target.getEntitlementsFilename());
build_tools::overwriteFileIfDifferentOrThrow (entitlementsFile, options.getEntitlementsFileContent());
build_tools::RelativePath entitlementsPath (entitlementsFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
addFile (FileOptions().withRelativePath (entitlementsPath));
}
String addProjectItem (const Project::Item& projectItem) const
{
if (modulesGroup != nullptr && projectItem.getParent() == *modulesGroup)
return addFileReference (rebaseFromProjectFolderToBuildTarget (getModuleFolderRelativeToProject (projectItem.getName())).toUnixStyle(),
"folder");
if (projectItem.isGroup())
{
StringArray childIDs;
for (int i = 0; i < projectItem.getNumChildren(); ++i)
{
auto child = projectItem.getChild (i);
auto childID = addProjectItem (child);
if (childID.isNotEmpty() && ! child.shouldBeAddedToXcodeResources())
childIDs.add (childID);
}
if (childIDs.isEmpty())
return {};
return addGroup (projectItem, childIDs);
}
if (projectItem.shouldBeAddedToTargetProject() && projectItem.shouldBeAddedToTargetExporter (*this))
{
auto itemPath = projectItem.getFilePath();
build_tools::RelativePath path;
if (itemPath.startsWith ("${") || build_tools::isAbsolutePath (itemPath))
path = build_tools::RelativePath (itemPath, build_tools::RelativePath::unknown);
else
path = build_tools::RelativePath (projectItem.getFile(), getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
if (path.hasFileExtension (".r"))
return addRezFile (projectItem, path);
XcodeTarget* xcodeTarget = nullptr;
if (projectItem.isModuleCode() && projectItem.shouldBeCompiled())
xcodeTarget = getTargetOfType (project.getTargetTypeFromFilePath (projectItem.getFile(), false));
return addFile (FileOptions().withRelativePath (path)
.withCompilerFlags (compilerFlagSchemesMap[projectItem.getCompilerFlagSchemeString()].get())
.withCompilationEnabled (projectItem.shouldBeCompiled())
.withAddToBinaryResourcesEnabled (projectItem.shouldBeAddedToBinaryResources())
.withAddToXcodeResourcesEnabled (projectItem.shouldBeAddedToXcodeResources())
.withInhibitWarningsEnabled (projectItem.shouldInhibitWarnings())
.withSkipPCHEnabled (isPCHEnabledForAnyConfigurations() && projectItem.shouldSkipPCH())
.withXcodeTarget (xcodeTarget));
}
return {};
}
String addFramework (const String& frameworkName) const
{
auto path = frameworkName;
auto isRelativePath = path.startsWith ("../");
if (! build_tools::isAbsolutePath (path) && ! isRelativePath)
path = "System/Library/Frameworks/" + path;
if (! path.endsWithIgnoreCase (".framework"))
path << ".framework";
auto fileRefID = createFileRefID (path);
addFileReference (((build_tools::isAbsolutePath (frameworkName) || isRelativePath) ? "" : "${SDKROOT}/") + path);
frameworkFileIDs.add (fileRefID);
return addBuildFile (FileOptions().withPath (path)
.withFileRefID (fileRefID));
}
String addCustomFramework (String frameworkPath) const
{
if (! frameworkPath.endsWithIgnoreCase (".framework"))
frameworkPath << ".framework";
auto fileRefID = createFileRefID (frameworkPath);
auto fileType = getFileType (frameworkPath);
addFileOrFolderReference (frameworkPath, "<group>", fileType);
frameworkFileIDs.add (fileRefID);
return addBuildFile (FileOptions().withPath (frameworkPath)
.withFileRefID (fileRefID));
}
String addEmbeddedFramework (const String& path) const
{
auto fileRefID = createFileRefID (path);
auto filename = build_tools::RelativePath (path, build_tools::RelativePath::unknown).getFileName();
auto fileType = getFileType (path);
addFileOrFolderReference (path, "<group>", fileType);
auto fileID = createID (path + "buildref");
ValueTree v (fileID + " /* " + filename + " */");
v.setProperty ("isa", "PBXBuildFile", nullptr);
v.setProperty ("fileRef", fileRefID, nullptr);
v.setProperty ("settings", "{ ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }", nullptr);
addObject (v);
frameworkFileIDs.add (fileRefID);
return fileID;
}
void addGroup (const String& groupID, const String& groupName, const StringArray& childIDs) const
{
ValueTree v (groupID);
v.setProperty ("isa", "PBXGroup", nullptr);
v.setProperty ("children", indentParenthesisedList (childIDs), nullptr);
v.setProperty (Ids::name, groupName, nullptr);
v.setProperty ("sourceTree", "<group>", nullptr);
addObject (v);
}
String addGroup (const Project::Item& item, StringArray& childIDs) const
{
auto groupName = item.getName();
auto groupID = getIDForGroup (item);
addGroup (groupID, groupName, childIDs);
return groupID;
}
void addProjectConfig (const String& configName, const StringArray& buildSettings) const
{
ValueTree v (createID ("projectconfigid_" + configName));
v.setProperty ("isa", "XCBuildConfiguration", nullptr);
v.setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
v.setProperty (Ids::name, configName, nullptr);
addObject (v);
}
void addConfigList (XcodeTarget& target, const String& listID) const
{
ValueTree v (listID);
v.setProperty ("isa", "XCConfigurationList", nullptr);
v.setProperty ("buildConfigurations", indentParenthesisedList (target.configIDs), nullptr);
v.setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
v.setProperty ("defaultConfigurationName", getConfiguration (0)->getName(), nullptr);
addObject (v);
}
void addProjectConfigList (const String& listID) const
{
auto buildConfigs = objects.getChildWithName ("XCBuildConfiguration");
jassert (buildConfigs.isValid());
StringArray configIDs;
for (const auto& child : buildConfigs)
configIDs.add (child.getType().toString());
ValueTree v (listID);
v.setProperty ("isa", "XCConfigurationList", nullptr);
v.setProperty ("buildConfigurations", indentParenthesisedList (configIDs), nullptr);
v.setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
v.setProperty ("defaultConfigurationName", getConfiguration (0)->getName(), nullptr);
addObject (v);
}
void addProjectObject() const
{
ValueTree v (createID ("__root"));
v.setProperty ("isa", "PBXProject", nullptr);
v.setProperty ("attributes", indentBracedList (getProjectObjectAttributes()), nullptr);
v.setProperty ("buildConfigurationList", createID ("__projList"), nullptr);
v.setProperty ("compatibilityVersion", "Xcode 3.2", nullptr);
v.setProperty ("hasScannedForEncodings", (int) 0, nullptr);
v.setProperty ("knownRegions", indentParenthesisedList ({ "en", "Base" }), nullptr);
v.setProperty ("mainGroup", createID ("__mainsourcegroup"), nullptr);
v.setProperty ("projectDirPath", "\"\"", nullptr);
if (! subprojectReferences.isEmpty())
{
StringArray projectReferences;
for (auto& reference : subprojectReferences)
projectReferences.add (indentBracedList ({ "ProductGroup = " + reference.productGroup, "ProjectRef = " + reference.projectRef }, 1));
v.setProperty ("projectReferences", indentParenthesisedList (projectReferences), nullptr);
}
v.setProperty ("projectRoot", "\"\"", nullptr);
v.setProperty ("targets", indentParenthesisedList (targetIDs), nullptr);
addObject (v);
}
//==============================================================================
void removeMismatchedXcuserdata() const
{
if (shouldKeepCustomXcodeSchemes())
return;
auto xcuserdata = getProjectBundle().getChildFile ("xcuserdata");
if (! xcuserdata.exists())
return;
if (! xcuserdataMatchesTargets (xcuserdata))
{
xcuserdata.deleteRecursively();
getProjectBundle().getChildFile ("xcshareddata").getChildFile ("xcschemes").deleteRecursively();
getProjectBundle().getChildFile ("project.xcworkspace").deleteRecursively();
}
}
bool xcuserdataMatchesTargets (const File& xcuserdata) const
{
for (auto& plist : xcuserdata.findChildFiles (File::findFiles, true, "xcschememanagement.plist"))
if (! xcschemeManagementPlistMatchesTargets (plist))
return false;
return true;
}
static StringArray parseNamesOfTargetsFromPlist (const XmlElement& dictXML)
{
for (auto* schemesKey : dictXML.getChildWithTagNameIterator ("key"))
{
if (schemesKey->getAllSubText().trim().equalsIgnoreCase ("SchemeUserState"))
{
if (auto* dict = schemesKey->getNextElement())
{
if (dict->hasTagName ("dict"))
{
StringArray names;
for (auto* key : dict->getChildWithTagNameIterator ("key"))
names.add (key->getAllSubText().upToLastOccurrenceOf (".xcscheme", false, false).trim());
names.sort (false);
return names;
}
}
}
}
return {};
}
StringArray getNamesOfTargets() const
{
StringArray names;
for (auto& target : targets)
names.add (target->getXcodeSchemeName());
names.sort (false);
return names;
}
bool xcschemeManagementPlistMatchesTargets (const File& plist) const
{
if (auto xml = parseXML (plist))
if (auto* dict = xml->getChildByName ("dict"))
return parseNamesOfTargetsFromPlist (*dict) == getNamesOfTargets();
return false;
}
StringArray getProjectObjectAttributes() const
{
std::map<String, String> attributes;
attributes["LastUpgradeCheck"] = "1300";
attributes["ORGANIZATIONNAME"] = getProject().getCompanyNameString().quoted();
if (projectType.isGUIApplication() || projectType.isAudioPlugin())
{
StringArray targetAttributes;
for (auto& target : targets)
targetAttributes.add (target->getTargetAttributes());
attributes["TargetAttributes"] = indentBracedList (targetAttributes, 1);
}
StringArray result;
for (const auto& attrib : attributes)
result.add (attrib.first + " = " + attrib.second);
return result;
}
//==============================================================================
void writeDefaultLaunchStoryboardFile() const
{
const auto storyboardFile = getTargetFolder().getChildFile (getDefaultLaunchStoryboardName() + ".storyboard");
build_tools::writeStreamToFile (storyboardFile, [&] (MemoryOutputStream& mo)
{
mo << String (BinaryData::LaunchScreen_storyboard);
});
addLaunchStoryboardFileReference (build_tools::RelativePath (storyboardFile,
getTargetFolder(),
build_tools::RelativePath::buildTargetFolder));
}
void addLaunchStoryboardFileReference (const build_tools::RelativePath& relativePath) const
{
auto path = relativePath.toUnixStyle();
auto refID = addFileReference (path);
auto fileID = addBuildFile (FileOptions().withPath (path)
.withFileRefID (refID));
resourceIDs.add (fileID);
resourceFileRefs.add (refID);
}
void addDefaultXcassetsFolders() const
{
const auto assetsPath = build_tools::createXcassetsFolderFromIcons (getIcons(),
getTargetFolder(),
project.getProjectFilenameRootString());
addFileReference (assetsPath.toUnixStyle());
resourceIDs.add (addBuildFile (FileOptions().withRelativePath (assetsPath)));
resourceFileRefs.add (createFileRefID (assetsPath));
}
//==============================================================================
static String indentBracedList (const StringArray& list, int depth = 0) { return indentList (list, '{', '}', ";", depth, true); }
static String indentParenthesisedList (const StringArray& list, int depth = 0) { return indentList (list, '(', ')', ",", depth, false); }
static String indentList (StringArray list, char openBracket, char closeBracket, const String& separator, int extraTabs, bool shouldSort)
{
auto content = [extraTabs, shouldSort, &list, &separator]() -> String
{
if (list.isEmpty())
return "";
if (shouldSort)
list.sort (true);
auto tabs = String::repeatedString ("\t", extraTabs + 4);
return tabs + list.joinIntoString (separator + "\n" + tabs) + separator + "\n";
}();
return openBracket + String ("\n")
+ content
+ String::repeatedString ("\t", extraTabs + 3) + closeBracket;
}
String createID (String rootString) const
{
if (rootString.startsWith ("${"))
rootString = rootString.fromFirstOccurrenceOf ("}/", false, false);
rootString += project.getProjectUIDString();
return MD5 (rootString.toUTF8()).toHexString().substring (0, 24).toUpperCase();
}
String createFileRefID (const build_tools::RelativePath& path) const { return createFileRefID (path.toUnixStyle()); }
String createFileRefID (const String& path) const { return createID ("__fileref_" + path); }
String getIDForGroup (const Project::Item& item) const { return createID (item.getID()); }
bool shouldFileBeCompiledByDefault (const File& file) const override
{
return file.hasFileExtension (sourceFileExtensions);
}
//==============================================================================
void updateOldOrientationSettings()
{
jassert (iOS);
StringArray orientationSettingStrings { getSetting (Ids::iPhoneScreenOrientation).getValue().toString(),
getSetting (Ids::iPadScreenOrientation).getValue().toString() };
for (int i = 0; i < 2; ++i)
{
auto& settingsString = orientationSettingStrings[i];
if (settingsString.isNotEmpty())
{
Array<var> orientations;
if (settingsString.contains ("portrait")) orientations.add ("UIInterfaceOrientationPortrait");
if (settingsString.contains ("landscape")) orientations.addArray ({ "UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight" });
if (! orientations.isEmpty())
{
if (i == 0)
iPhoneScreenOrientationValue = orientations;
else
iPadScreenOrientationValue = orientations;
}
}
}
}
void addObject (ValueTree data) const
{
if (auto* type = data.getPropertyPointer ("isa"))
{
auto objs = objects.getOrCreateChildWithName (type->toString(), nullptr);
auto objectID = data.getType();
auto numChildren = objs.getNumChildren();
for (int i = 0; i < numChildren; ++i)
{
auto obj = objs.getChild (i);
auto childID = obj.getType();
if (objectID < childID)
{
objs.addChild (data, i, nullptr);
return;
}
if (objectID == childID)
{
jassert (obj.isEquivalentTo (data));
return;
}
}
objs.appendChild (data, nullptr);
return;
}
jassertfalse;
}
//==============================================================================
friend class CLionProjectExporter;
bool xcodeCanUseDwarf;
OwnedArray<XcodeTarget> targets;
mutable ValueTree objects { "objects" };
mutable StringArray resourceIDs, sourceIDs, targetIDs, frameworkFileIDs, embeddedFrameworkIDs,
rezFileIDs, resourceFileRefs, subprojectFileIDs, subprojectDependencyIDs;
struct SubprojectReferenceInfo
{
String productGroup, projectRef;
};
mutable Array<SubprojectReferenceInfo> subprojectReferences;
mutable File menuNibFile, iconFile;
mutable StringArray buildProducts;
const bool iOS;
ValueWithDefault applicationCategoryValue,
customPListValue, pListPrefixHeaderValue, pListPreprocessValue,
subprojectsValue,
validArchsValue,
extraFrameworksValue, frameworkSearchPathsValue, extraCustomFrameworksValue, embeddedFrameworksValue,
postbuildCommandValue, prebuildCommandValue,
duplicateAppExResourcesFolderValue, iosDeviceFamilyValue, iPhoneScreenOrientationValue,
iPadScreenOrientationValue, customXcodeResourceFoldersValue, customXcassetsFolderValue,
appSandboxValue, appSandboxInheritanceValue, appSandboxOptionsValue,
hardenedRuntimeValue, hardenedRuntimeOptionsValue,
microphonePermissionNeededValue, microphonePermissionsTextValue,
cameraPermissionNeededValue, cameraPermissionTextValue,
bluetoothPermissionNeededValue, bluetoothPermissionTextValue,
sendAppleEventsPermissionNeededValue, sendAppleEventsPermissionTextValue,
uiFileSharingEnabledValue, uiSupportsDocumentBrowserValue, uiStatusBarHiddenValue, uiRequiresFullScreenValue, documentExtensionsValue, iosInAppPurchasesValue,
iosContentSharingValue, iosBackgroundAudioValue, iosBackgroundBleValue, iosPushNotificationsValue, iosAppGroupsValue, iCloudPermissionsValue,
networkingMulticastValue, iosDevelopmentTeamIDValue, iosAppGroupsIDValue, keepCustomXcodeSchemesValue, useHeaderMapValue, customLaunchStoryboardValue,
exporterBundleIdentifierValue, suppressPlistResourceUsageValue, useLegacyBuildSystemValue, buildNumber;
JUCE_DECLARE_NON_COPYABLE (XcodeProjectExporter)
};
|
BastienC09/JUCE
|
modules/juce_gui_basics/windows/juce_TooltipWindow.h
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A window that displays a pop-up tooltip when the mouse hovers over another component.
To enable tooltips in your app, just create a single instance of a TooltipWindow
object. Note that if you instantiate more than one instance of this class with the
same parentComponent (even if both TooltipWindow's parentComponent is nil), you'll
end up with multiple tooltips being shown! To avoid this use a SharedResourcePointer
to instantiate the TooltipWindow only once.
For audio plug-ins (which should not be opening native windows) it is better
to add a TooltipWindow as a member variable to the editor and ensure that the
editor is the parentComponent of your TooltipWindow. This will ensure that your
TooltipWindow is scaled according to your editor and the DAWs scaling setting.
The TooltipWindow object will then stay invisible, waiting until the mouse
hovers for the specified length of time - it will then see if it's currently
over a component which implements the TooltipClient interface, and if so,
it will make itself visible to show the tooltip in the appropriate place.
@see TooltipClient, SettableTooltipClient, SharedResourcePointer
@tags{GUI}
*/
class JUCE_API TooltipWindow : public Component,
private Timer
{
public:
//==============================================================================
/** Creates a tooltip window.
Make sure your app only creates one instance of this class, otherwise you'll
get multiple overlaid tooltips appearing. The window will initially be invisible
and will make itself visible when it needs to display a tip.
To change the style of tooltips, see the LookAndFeel class for its tooltip
methods.
@param parentComponent if set to nullptr, the TooltipWindow will appear on the desktop,
otherwise the tooltip will be added to the given parent
component.
@param millisecondsBeforeTipAppears the time for which the mouse has to stay still
before a tooltip will be shown
@see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipBounds
*/
explicit TooltipWindow (Component* parentComponent = nullptr,
int millisecondsBeforeTipAppears = 700);
/** Destructor. */
~TooltipWindow() override;
//==============================================================================
/** Changes the time before the tip appears.
This lets you change the value that was set in the constructor.
*/
void setMillisecondsBeforeTipAppears (int newTimeMs = 700) noexcept;
/** Can be called to manually force a tip to be shown at a particular location. */
void displayTip (Point<int> screenPosition, const String& text);
/** Can be called to manually hide the tip if it's showing. */
void hideTip();
/** Asks a component for its tooltip.
This can be overridden if you need custom lookup behaviour or to modify the strings.
*/
virtual String getTipFor (Component&);
//==============================================================================
/** A set of colour IDs to use to change the colour of various aspects of the tooltip.
These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
methods.
@see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
*/
enum ColourIds
{
backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
textColourId = 0x1001c00, /**< The colour to use for the text. */
outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
};
//==============================================================================
/** This abstract base class is implemented by LookAndFeel classes to provide
window drawing functionality.
*/
struct JUCE_API LookAndFeelMethods
{
virtual ~LookAndFeelMethods() = default;
/** returns the bounds for a tooltip at the given screen coordinate, constrained within the given desktop area. */
virtual Rectangle<int> getTooltipBounds (const String& tipText, Point<int> screenPos, Rectangle<int> parentArea) = 0;
virtual void drawTooltip (Graphics&, const String& text, int width, int height) = 0;
};
//==============================================================================
/** @internal */
float getDesktopScaleFactor() const override;
private:
//==============================================================================
Point<float> lastMousePos;
Component* lastComponentUnderMouse = nullptr;
String tipShowing, lastTipUnderMouse;
int millisecondsBeforeTipAppears;
int mouseClicks = 0, mouseWheelMoves = 0;
unsigned int lastCompChangeTime = 0, lastHideTime = 0;
bool reentrant = false;
std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override;
void paint (Graphics&) override;
void mouseEnter (const MouseEvent&) override;
void timerCallback() override;
void updatePosition (const String&, Point<int>, Rectangle<int>);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow)
};
} // namespace juce
|
GMahmoud/cartographer_android
|
src/cartographer/to_string.h
|
<filename>src/cartographer/to_string.h
#ifndef CARTOGRAPHER_CUSTOM_TOSTR
#define CARTOGRAPHER_CUSTOM_TOSTR
#include <sstream>
template <typename T>
std::string to_string(const T& value) {
std::stringstream ss;
ss << value;
return ss.str();
}
#endif //CARTOGRAPHER_CUSTOM_TOSTR
|
GMahmoud/cartographer_android
|
src/cartographer_generic/test_heritage.h
|
<reponame>GMahmoud/cartographer_android
/*
* test_header.h
*
* Created on: Aug 7, 2017
* Author: maghob
*/
#ifndef SRC_CARTOGRAPHER_GENERIC_TEST_HERITAGE_H_
#define SRC_CARTOGRAPHER_GENERIC_TEST_HERITAGE_H_
#include <cstdarg>
#include <string>
#include "ceres/internal/port.h"
#include <vector>
#include "ceres/ordered_groups.h"
#include "ceres/graph.h"
#include "ceres/types.h"
#include "ceres/program.h"
namespace ceres {
namespace carto {
using std::string;
using namespace std;
using namespace ceres::internal;
#if (defined(__GNUC__) || defined(__clang__))
// Tell the compiler to do printf format string checking if the compiler
// supports it; see the 'format' attribute in
// <http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html>.
//
// N.B.: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
#define CERES_PRINTF_ATTRIBUTE(string_index, first_to_check) \
__attribute__((__format__ (__printf__, string_index, first_to_check)))
#define CERES_SCANF_ATTRIBUTE(string_index, first_to_check) \
__attribute__((__format__ (__scanf__, string_index, first_to_check)))
#else
#define CERES_PRINTF_ATTRIBUTE(string_index, first_to_check)
#endif
// Return a C++ string.
extern std::string StringPrintf(const char* format, ...)
// Tell the compiler to do printf format string checking.
CERES_PRINTF_ATTRIBUTE(1, 2);
// Store result into a supplied string and return it.
extern const std::string& SStringPrintf(std::string* dst, const char* format, ...)
// Tell the compiler to do printf format string checking.
CERES_PRINTF_ATTRIBUTE(2, 3);
// Append result to a supplied string.
extern void StringAppendF(std::string* dst, const char* format, ...)
// Tell the compiler to do printf format string checking.
CERES_PRINTF_ATTRIBUTE(2, 3);
// Lower-level routine that takes a va_list and appends to a specified string.
// All other routines are just convenience wrappers around it.
extern void StringAppendV(std::string* dst, const char* format, va_list ap);
#undef CERES_PRINTF_ATTRIBUTE
void OrderingToGroupSizes(const ParameterBlockOrdering* ordering,
std::vector<int>* group_sizes);
bool ParameterBlocksAreFinite(const Program& program,string* message);
int FindInvalidValue(const int size, const double* x);
void AppendArrayToString(const int size, const double* x, string* result);
bool IsFeasible(const Program& program, string* message);
//Program* CreateReducedProgram(Program* program, vector<double*>* removed_parameter_blocks, double* fixed_cost,string* error);
} // namespace internal
} // namespace ceres
#endif /* SRC_CARTOGRAPHER_GENERIC_TEST_HERITAGE_H_ */
|
GMahmoud/cartographer_android
|
src/cartographer_generic/test.h
|
#ifndef SRC_CARTOGRAPHER_GENERIC_TEST_H_
#define SRC_CARTOGRAPHER_GENERIC_TEST_H_
#include "cartographer_generic/test_heritage.h"
#include <cmath>
#include <string>
#include <vector>
#include "ceres/crs_matrix.h"
#include "ceres/internal/macros.h"
#include "ceres/internal/port.h"
#include "ceres/iteration_callback.h"
#include "ceres/ordered_groups.h"
#include "ceres/types.h"
#include "ceres/internal/disable_warnings.h"
#include "ceres/problem.h"
#include "ceres/solver.h"
//#include "cartographer_generic/test/problem_test.h"
namespace ceres{
// Interface for non-linear least squares solvers.
class test {
public:
virtual ~test();
struct Options {
Options() {
minimizer_type = TRUST_REGION;
line_search_direction_type = LBFGS;
line_search_type = WOLFE;
nonlinear_conjugate_gradient_type = FLETCHER_REEVES;
max_lbfgs_rank = 20;
use_approximate_eigenvalue_bfgs_scaling = false;
line_search_interpolation_type = CUBIC;
min_line_search_step_size = 1e-9;
line_search_sufficient_function_decrease = 1e-4;
max_line_search_step_contraction = 1e-3;
min_line_search_step_contraction = 0.6;
max_num_line_search_step_size_iterations = 20;
max_num_line_search_direction_restarts = 5;
line_search_sufficient_curvature_decrease = 0.9;
max_line_search_step_expansion = 10.0;
trust_region_strategy_type = LEVENBERG_MARQUARDT;
dogleg_type = TRADITIONAL_DOGLEG;
use_nonmonotonic_steps = false;
max_consecutive_nonmonotonic_steps = 5;
max_num_iterations = 50;
max_solver_time_in_seconds = 1e9;
num_threads = 1;
initial_trust_region_radius = 1e4;
max_trust_region_radius = 1e16;
min_trust_region_radius = 1e-32;
min_relative_decrease = 1e-3;
min_lm_diagonal = 1e-6;
max_lm_diagonal = 1e32;
max_num_consecutive_invalid_steps = 5;
function_tolerance = 1e-6;
gradient_tolerance = 1e-10;
parameter_tolerance = 1e-8;
#if defined(CERES_NO_SUITESPARSE) && defined(CERES_NO_CXSPARSE) && !defined(CERES_ENABLE_LGPL_CODE) // NOLINT
linear_solver_type = DENSE_QR;
#else
linear_solver_type = SPARSE_NORMAL_CHOLESKY;
#endif
preconditioner_type = JACOBI;
visibility_clustering_type = CANONICAL_VIEWS;
dense_linear_algebra_library_type = EIGEN;
// Choose a default sparse linear algebra library in the order:
//
// SUITE_SPARSE > CX_SPARSE > EIGEN_SPARSE > NO_SPARSE
sparse_linear_algebra_library_type = NO_SPARSE;
#if !defined(CERES_NO_SUITESPARSE)
sparse_linear_algebra_library_type = SUITE_SPARSE;
#else
#if !defined(CERES_NO_CXSPARSE)
sparse_linear_algebra_library_type = CX_SPARSE;
#else
#if defined(CERES_USE_EIGEN_SPARSE)
sparse_linear_algebra_library_type = EIGEN_SPARSE;
#endif
#endif
#endif
num_linear_solver_threads = 1;
use_explicit_schur_complement = false;
use_postordering = false;
dynamic_sparsity = false;
min_linear_solver_iterations = 0;
max_linear_solver_iterations = 500;
eta = 1e-1;
jacobi_scaling = true;
use_inner_iterations = false;
inner_iteration_tolerance = 1e-3;
logging_type = PER_MINIMIZER_ITERATION;
minimizer_progress_to_stdout = false;
trust_region_problem_dump_directory = "/tmp";
trust_region_problem_dump_format_type = TEXTFILE;
check_gradients = false;
gradient_check_relative_precision = 1e-8;
gradient_check_numeric_derivative_relative_step_size = 1e-6;
update_state_every_iteration = false;
}
bool IsValid(std::string* error) const;
MinimizerType minimizer_type;
LineSearchDirectionType line_search_direction_type;
LineSearchType line_search_type;
NonlinearConjugateGradientType nonlinear_conjugate_gradient_type;
int max_lbfgs_rank;
bool use_approximate_eigenvalue_bfgs_scaling;
LineSearchInterpolationType line_search_interpolation_type;
double min_line_search_step_size;
double line_search_sufficient_function_decrease;
double max_line_search_step_contraction;
double min_line_search_step_contraction;
int max_num_line_search_step_size_iterations;
int max_num_line_search_direction_restarts;
double line_search_sufficient_curvature_decrease;
double max_line_search_step_expansion;
TrustRegionStrategyType trust_region_strategy_type;
DoglegType dogleg_type;
bool use_nonmonotonic_steps;
int max_consecutive_nonmonotonic_steps;
int max_num_iterations;
double max_solver_time_in_seconds;
int num_threads;
double initial_trust_region_radius;
double max_trust_region_radius;
double min_trust_region_radius;
double min_relative_decrease;
double min_lm_diagonal;
double max_lm_diagonal;
int max_num_consecutive_invalid_steps;
double function_tolerance;
double gradient_tolerance;
double parameter_tolerance;
LinearSolverType linear_solver_type;
PreconditionerType preconditioner_type;
VisibilityClusteringType visibility_clustering_type;
DenseLinearAlgebraLibraryType dense_linear_algebra_library_type;
SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type;
int num_linear_solver_threads;
shared_ptr<ParameterBlockOrdering> linear_solver_ordering;
bool use_explicit_schur_complement;
bool use_postordering;
bool dynamic_sparsity;
bool use_inner_iterations;
shared_ptr<ParameterBlockOrdering> inner_iteration_ordering;
double inner_iteration_tolerance;
int min_linear_solver_iterations;
int max_linear_solver_iterations;
double eta;
bool jacobi_scaling;
LoggingType logging_type;
bool minimizer_progress_to_stdout;
std::vector<int> trust_region_minimizer_iterations_to_dump;
std::string trust_region_problem_dump_directory;
DumpFormatType trust_region_problem_dump_format_type;
bool check_gradients;
double gradient_check_relative_precision;
double gradient_check_numeric_derivative_relative_step_size;
bool update_state_every_iteration;
std::vector<IterationCallback*> callbacks;
Solver::Options solver_option_;
};
struct Summary {
Summary();
std::string BriefReport() const;
std::string FullReport() const;
bool IsSolutionUsable() const;
MinimizerType minimizer_type;
TerminationType termination_type;
std::string message;
double initial_cost;
double final_cost;
double fixed_cost;
std::vector<IterationSummary> iterations;
int num_successful_steps;
int num_unsuccessful_steps;
int num_inner_iteration_steps;
int num_line_search_steps;
double preprocessor_time_in_seconds;
double minimizer_time_in_seconds;
double postprocessor_time_in_seconds;
double total_time_in_seconds;
double linear_solver_time_in_seconds;
double residual_evaluation_time_in_seconds;
double jacobian_evaluation_time_in_seconds;
double inner_iteration_time_in_seconds;
double line_search_cost_evaluation_time_in_seconds;
double line_search_gradient_evaluation_time_in_seconds;
double line_search_polynomial_minimization_time_in_seconds;
double line_search_total_time_in_seconds;
int num_parameter_blocks;
int num_parameters;
int num_effective_parameters;
int num_residual_blocks;
int num_residuals;
int num_parameter_blocks_reduced;
int num_parameters_reduced;
int num_effective_parameters_reduced;
int num_residual_blocks_reduced;
int num_residuals_reduced;
bool is_constrained;
int num_threads_given;
int num_threads_used;
int num_linear_solver_threads_given;
int num_linear_solver_threads_used;
LinearSolverType linear_solver_type_given;
LinearSolverType linear_solver_type_used;
std::vector<int> linear_solver_ordering_given;
std::vector<int> linear_solver_ordering_used;
std::string schur_structure_given;
std::string schur_structure_used;
bool inner_iterations_given;
bool inner_iterations_used;
std::vector<int> inner_iteration_ordering_given;
std::vector<int> inner_iteration_ordering_used;
PreconditionerType preconditioner_type_given;
PreconditionerType preconditioner_type_used;
VisibilityClusteringType visibility_clustering_type;
TrustRegionStrategyType trust_region_strategy_type;
DoglegType dogleg_type;
DenseLinearAlgebraLibraryType dense_linear_algebra_library_type;
SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type;
LineSearchDirectionType line_search_direction_type;
LineSearchType line_search_type;
LineSearchInterpolationType line_search_interpolation_type;
NonlinearConjugateGradientType nonlinear_conjugate_gradient_type;
int max_lbfgs_rank;
};
virtual void Solve(const test::Options& options,
Problem* problem,
test::Summary* summary);
};
void Solve(const test::Options& options,
Problem* problem,
test::Summary* summary);
} // namespace ceres
#include "ceres/internal/reenable_warnings.h"
#endif // CERES_PUBLIC_SOLVER_H_
|
GMahmoud/cartographer_android
|
src/cartographer_generic/sensor_bridge.h
|
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_GENERIC_SENSOR_BRIDGE_H_
#define CARTOGRAPHER_GENERIC_SENSOR_BRIDGE_H_
#include <memory>
#include "cartographer/mapping/trajectory_builder.h"
#include "cartographer/sensor/imu_data.h"
#include "cartographer/sensor/odometry_data.h"
#include "cartographer/transform/rigid_transform.h"
#include "cartographer/transform/transform.h"
#include "cartographer_generic/tf_bridge.h"
#include "cartographer_generic_msgs/LaserScan.h"
#include "cartographer_generic_msgs/Odometry.h"
namespace cartographer_generic {
// Converts ROS messages into SensorData in tracking frame for the MapBuilder.
class SensorBridge {
public:
explicit SensorBridge(
int num_subdivisions_per_laser_scan, const string& tracking_frame,
double lookup_transform_timeout_sec, /*tf2_ros::Buffer* tf_buffer,*/
::cartographer::mapping::TrajectoryBuilder* trajectory_builder);
SensorBridge(const SensorBridge&) = delete;
SensorBridge& operator=(const SensorBridge&) = delete;
std::unique_ptr<::cartographer::sensor::OdometryData> ToOdometryData(
::cartographer_generic_msgs::Odometry::Ptr& msg);
void HandleOdometryMessage(const string& sensor_id,
::cartographer_generic_msgs::Odometry::Ptr& msg);
// std::unique_ptr<::cartographer::sensor::ImuData> ToImuData(
// const sensor_msgs::Imu::Ptr& msg);
// void HandleImuMessage(const string& sensor_id,
// const sensor_msgs::Imu::Ptr& msg);
void HandleLaserScanMessage(const string& sensor_id,
::cartographer_generic_msgs::LaserScan::Ptr& msg);
// void HandleMultiEchoLaserScanMessage(
// const string& sensor_id,
// const sensor_msgs::MultiEchoLaserScan::Ptr& msg);
// void HandlePointCloud2Message(const string& sensor_id,
// const sensor_msgs::PointCloud2::Ptr& msg);
const TfBridge& tf_bridge() const;
private:
void HandleLaserScan(const string& sensor_id,
::cartographer::common::Time start_time,
const string& frame_id,
const ::cartographer::sensor::PointCloud& points,
double seconds_between_points);
void HandleRangefinder(const string& sensor_id,
::cartographer::common::Time time,
const string& frame_id,
const ::cartographer::sensor::PointCloud& ranges);
const int num_subdivisions_per_laser_scan_;
const TfBridge tf_bridge_;
::cartographer::mapping::TrajectoryBuilder* const trajectory_builder_;
};
} // namespace cartographer_generic
#endif // CARTOGRAPHER_GENERIC_SENSOR_BRIDGE_H_
|
GMahmoud/cartographer_android
|
src/cartographer_generic/map_builder_bridge.h
|
<gh_stars>1-10
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_GENERIC_MAP_BUILDER_BRIDGE_H_
#define CARTOGRAPHER_GENERIC_MAP_BUILDER_BRIDGE_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include "cartographer/mapping/map_builder.h"
#include "cartographer/mapping/proto/trajectory_builder_options.pb.h"
#include "cartographer_generic/node_options.h"
#include "cartographer_generic/sensor_bridge.h"
#include "cartographer_generic/tf_bridge.h"
#include "cartographer_generic/trajectory_options.h"
#include "cartographer_generic_msgs/SubmapList.h"
#include "cartographer_generic_msgs/SubmapQuery.h"
#include "cartographer_generic_msgs/MarkerArray.h"
namespace cartographer_generic {
class MapBuilderBridge {
public:
struct TrajectoryState {
cartographer::mapping::TrajectoryBuilder::PoseEstimate pose_estimate;
cartographer::transform::Rigid3d local_to_map;
std::unique_ptr<cartographer::transform::Rigid3d> published_to_tracking;
TrajectoryOptions trajectory_options;
};
MapBuilderBridge(const NodeOptions& node_options/*, tf2_ros::Buffer* tf_buffer*/);
MapBuilderBridge(const MapBuilderBridge&) = delete;
MapBuilderBridge& operator=(const MapBuilderBridge&) = delete;
//void LoadMap(const std::string& map_filename);
int AddTrajectory(const std::unordered_set<string>& expected_sensor_ids,
const TrajectoryOptions& trajectory_options);
void FinishTrajectory(int trajectory_id);
cartographer_generic_msgs::SubmapList GetSubmapList();
bool HandleSubmapQuery(cartographer_generic_msgs::SubmapQuery::Request& request,
cartographer_generic_msgs::SubmapQuery::Response& response);
std::unordered_map<int, TrajectoryState> GetTrajectoryStates();
cartographer_generic_msgs::MarkerArray GetTrajectoryNodeList(::cartographer::common::Time time);
//visualization_msgs::MarkerArray GetConstraintList();
SensorBridge* sensor_bridge(int trajectory_id);
private:
const NodeOptions node_options_;
cartographer::mapping::MapBuilder map_builder_;
//tf2_ros::Buffer* const tf_buffer_;
// These are keyed with 'trajectory_id'.
std::unordered_map<int, TrajectoryOptions> trajectory_options_;
std::unordered_map<int, std::unique_ptr<SensorBridge>> sensor_bridges_;
};
} // namespace cartographer_generic
#endif // CARTOGRAPHER_GENERIC_MAP_BUILDER_BRIDGE_H_
|
GMahmoud/cartographer_android
|
src/cartographer/sensor/collator.h
|
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_SENSOR_COLLATOR_H_
#define CARTOGRAPHER_SENSOR_COLLATOR_H_
#include <functional>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "cartographer/sensor/data.h"
#include "cartographer/sensor/ordered_multi_queue.h"
namespace cartographer {
namespace sensor {
class Collator {
public:
using Callback = std::function<void(const string&, std::unique_ptr<Data>)>;
Collator() {}
Collator(const Collator&) = delete;
Collator& operator=(const Collator&) = delete;
// Adds a trajectory to produce sorted sensor output for. Calls 'callback'
// for each collated sensor data.
void AddTrajectory(int trajectory_id,
const std::unordered_set<string>& expected_sensor_ids,
Callback callback);
// Marks 'trajectory_id' as finished.
void FinishTrajectory(int trajectory_id);
// Adds 'data' for 'trajectory_id' to be collated. 'data' must contain valid
// sensor data. Sensor packets with matching 'sensor_id' must be added in time
// order.
void AddSensorData(int trajectory_id, const string& sensor_id,
std::unique_ptr<Data> data);
// Dispatches all queued sensor packets. May only be called once.
// AddSensorData may not be called after Flush.
void Flush();
// Must only be called if at least one unfinished trajectory exists. Returns
// the ID of the trajectory that needs more data before the Collator is
// unblocked.
int GetBlockingTrajectoryId() const;
private:
// Queue keys are a pair of trajectory ID and sensor identifier.
OrderedMultiQueue queue_;
// Map of trajectory ID to all associated QueueKeys.
std::unordered_map<int, std::vector<QueueKey>> queue_keys_;
};
} // namespace sensor
} // namespace cartographer
#endif // CARTOGRAPHER_SENSOR_COLLATOR_H_
|
GMahmoud/cartographer_android
|
src/cartographer/io/color.h
|
/*
* Copyright 2017 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_IO_COLOR_H_
#define CARTOGRAPHER_IO_COLOR_H_
#include <array>
namespace cartographer {
namespace io {
// TODO(hrapp): Should probably be represented as floats.
using Color = std::array<uint8_t, 3>;
// A function for on-demand generation of a color palette, with every two
// direct successors having large contrast.
Color GetColor(int id);
} // namespace io
} // namespace cartographer
#endif // CARTOGRAPHER_IO_COLOR_H_
|
GMahmoud/cartographer_android
|
src/cartographer/mapping/trajectory_builder.h
|
<gh_stars>1-10
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_MAPPING_TRAJECTORY_BUILDER_H_
#define CARTOGRAPHER_MAPPING_TRAJECTORY_BUILDER_H_
#include <functional>
#include <memory>
#include <string>
#include "cartographer/common/lua_parameter_dictionary.h"
#include "cartographer/common/make_unique.h"
#include "cartographer/common/port.h"
#include "cartographer/common/time.h"
#include "cartographer/mapping/proto/trajectory_builder_options.pb.h"
#include "cartographer/mapping/submaps.h"
#include "cartographer/sensor/data.h"
#include "cartographer/sensor/point_cloud.h"
#include "cartographer/sensor/range_data.h"
namespace cartographer {
namespace mapping {
proto::TrajectoryBuilderOptions CreateTrajectoryBuilderOptions(
common::LuaParameterDictionary* const parameter_dictionary);
// This interface is used for both 2D and 3D SLAM.
class TrajectoryBuilder {
public:
// Represents a newly computed pose. 'pose' is the end-user visualization of
// orientation and 'point_cloud' is the point cloud, in the local map frame.
struct PoseEstimate {
PoseEstimate() = default;
PoseEstimate(common::Time time, const transform::Rigid3d& pose,
const sensor::PointCloud& point_cloud)
: time(time), pose(pose), point_cloud(point_cloud) {}
common::Time time = common::Time::min();
transform::Rigid3d pose = transform::Rigid3d::Identity();
sensor::PointCloud point_cloud;
};
TrajectoryBuilder() {}
virtual ~TrajectoryBuilder() {}
TrajectoryBuilder(const TrajectoryBuilder&) = delete;
TrajectoryBuilder& operator=(const TrajectoryBuilder&) = delete;
virtual const PoseEstimate& pose_estimate() const = 0;
virtual void AddSensorData(const string& sensor_id,
std::unique_ptr<sensor::Data> data) = 0;
void AddRangefinderData(const string& sensor_id, common::Time time,
const Eigen::Vector3f& origin,
const sensor::PointCloud& ranges) {
AddSensorData(sensor_id,
common::make_unique<sensor::Data>(
time, sensor::Data::Rangefinder{origin, ranges}));
}
void AddImuData(const string& sensor_id, common::Time time,
const Eigen::Vector3d& linear_acceleration,
const Eigen::Vector3d& angular_velocity) {
AddSensorData(sensor_id, common::make_unique<sensor::Data>(
time, sensor::Data::Imu{linear_acceleration,
angular_velocity}));
}
void AddOdometerData(const string& sensor_id, common::Time time,
const transform::Rigid3d& odometer_pose) {
AddSensorData(sensor_id,
common::make_unique<sensor::Data>(time, odometer_pose));
}
};
} // namespace mapping
} // namespace cartographer
#endif // CARTOGRAPHER_MAPPING_TRAJECTORY_BUILDER_H_
|
GMahmoud/cartographer_android
|
src/cartographer_generic_msgs/impl/PointCloud2Iterator.h
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Open Source Robotics Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Open Source Robotics Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CARTOGRAPHER_GENERIC_MSGS_IMPL_POINTCLOUD2ITERATOR_H
#define CARTOGRAPHER_GENERIC_MSGS_IMPL_POINTCLOUD2ITERATOR_H
#include <string>
#include <vector>
#include "cartographer_generic_msgs/PointCloud2.h"
namespace cartographer_generic_msgs
{
namespace impl
{
template<typename T, typename TT, typename U, typename C, template <typename> class V>
PointCloud2IteratorBase<T, TT, U, C, V>::PointCloud2IteratorBase() : data_char_(0), data_(0), data_end_(0)
{
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
PointCloud2IteratorBase<T, TT, U, C, V>::PointCloud2IteratorBase(C &cloud_msg, const std::string &field_name)
{
int offset = set_field(cloud_msg, field_name);
data_char_ = &(cloud_msg.data.front()) + offset;
data_ = reinterpret_cast<TT*>(data_char_);
data_end_ = reinterpret_cast<TT*>(&(cloud_msg.data.back()) + 1 + offset);
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
V<T>& PointCloud2IteratorBase<T, TT, U, C, V>::operator =(const V<T> &iter)
{
if (this != &iter)
{
point_step_ = iter.point_step_;
data_char_ = iter.data_char_;
data_ = iter.data_;
data_end_ = iter.data_end_;
is_bigendian_ = iter.is_bigendian_;
}
return *this;
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
TT& PointCloud2IteratorBase<T, TT, U, C, V>::operator [](size_t i) const
{
return *(data_ + i);
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
TT& PointCloud2IteratorBase<T, TT, U, C, V>::operator *() const
{
return *data_;
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
V<T>& PointCloud2IteratorBase<T, TT, U, C, V>::operator ++()
{
data_char_ += point_step_;
data_ = reinterpret_cast<TT*>(data_char_);
return *static_cast<V<T>*>(this);
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
V<T> PointCloud2IteratorBase<T, TT, U, C, V>::operator +(int i)
{
V<T> res = *static_cast<V<T>*>(this);
res.data_char_ += i*point_step_;
res.data_ = reinterpret_cast<TT*>(res.data_char_);
return res;
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
V<T>& PointCloud2IteratorBase<T, TT, U, C, V>::operator +=(int i)
{
data_char_ += i*point_step_;
data_ = reinterpret_cast<TT*>(data_char_);
return *static_cast<V<T>*>(this);
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
bool PointCloud2IteratorBase<T, TT, U, C, V>::operator !=(const V<T>& iter) const
{
return iter.data_ != data_;
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
V<T> PointCloud2IteratorBase<T, TT, U, C, V>::end() const
{
V<T> res = *static_cast<const V<T>*>(this);
res.data_ = data_end_;
return res;
}
template<typename T, typename TT, typename U, typename C, template <typename> class V>
int PointCloud2IteratorBase<T, TT, U, C, V>::set_field(const PointCloud2 &cloud_msg, const std::string &field_name)
{
is_bigendian_ = cloud_msg.is_bigendian;
point_step_ = cloud_msg.point_step;
// make sure the channel is valid
std::vector<PointField>::const_iterator field_iter = cloud_msg.fields.begin(), field_end =
cloud_msg.fields.end();
while ((field_iter != field_end) && (field_iter->name != field_name))
++field_iter;
if (field_iter == field_end) {
// Handle the special case of r,g,b,a (we assume they are understood as the channels of an rgb or rgba field)
if ((field_name == "r") || (field_name == "g") || (field_name == "b") || (field_name == "a"))
{
// Check that rgb or rgba is present
field_iter = cloud_msg.fields.begin();
while ((field_iter != field_end) && (field_iter->name != "rgb") && (field_iter->name != "rgba"))
++field_iter;
if (field_iter == field_end)
throw std::runtime_error("Field " + field_name + " does not exist");
if (field_name == "r")
{
if (is_bigendian_)
return field_iter->offset + 1;
else
return field_iter->offset + 2;
}
if (field_name == "g")
{
if (is_bigendian_)
return field_iter->offset + 2;
else
return field_iter->offset + 1;
}
if (field_name == "b")
{
if (is_bigendian_)
return field_iter->offset + 3;
else
return field_iter->offset + 0;
}
if (field_name == "a")
{
if (is_bigendian_)
return field_iter->offset + 0;
else
return field_iter->offset + 3;
}
} else
throw std::runtime_error("Field " + field_name + " does not exist");
}
return field_iter->offset;
}
} // namespace impl
} // namespace cartographer_generic_msgs
#endif //CARTOGRAPHER_GENERIC_MSGS_IMPL_POINTCLOUD2ITERATOR_H
|
GMahmoud/cartographer_android
|
src/cartographer_generic/node.h
|
<filename>src/cartographer_generic/node.h
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_GENERIC_NODE_H_
#define CARTOGRAPHER_GENERIC_NODE_H_
#include <map>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "cartographer/common/mutex.h"
#include "cartographer/mapping/pose_extrapolator.h"
#include "cartographer_generic/node_constants.h"
#include "cartographer_generic/node_options.h"
#include "cartographer_generic/trajectory_options.h"
#include "cartographer_generic_msgs/SensorTopics.h"
#include "cartographer_generic/map_builder_bridge.h"
#include "cartographer_generic_msgs/SubmapList.h"
#include "cartographer_generic_msgs/SubmapQuery.h"
#include "cartographer_generic_msgs/MarkerArray.h"
namespace cartographer_generic {
// Wires up ROS topics to SLAM.
class Node {
public:
Node(const NodeOptions& node_options/*, tf2_ros::Buffer* tf_buffer*/);
~Node();
Node(const Node&) = delete;
Node& operator=(const Node&) = delete;
// Finishes all yet active trajectories.
void FinishAllTrajectories();
// Starts the first trajectory with the default topics.
int StartTrajectory(const TrajectoryOptions& options);
//Callbacks
void LaserScanCallback (::cartographer_generic_msgs::LaserScan::Ptr& msg, const int trajectory_id);
void OdometryCallback(::cartographer_generic_msgs::Odometry::Ptr& msg, const int trajectory_id );
// Loads a persisted state to use as a map.
//void LoadMap(const std::string& map_filename);
MapBuilderBridge* map_builder_bridge();
::cartographer_generic_msgs::SubmapList GetSubmapList();
::cartographer_generic_msgs::MarkerArray GetTrajectoryNodeList(::cartographer::common::Time time);
cartographer::transform::Rigid3d GetTrajectoryStates();
bool HandleSubmapQuery(
::cartographer_generic_msgs::SubmapQuery::Request& request,
::cartographer_generic_msgs::SubmapQuery::Response& response);
private:
// Returns the set of topic names we want to subscribe to.
std::unordered_set<std::string> ComputeExpectedTopics(
const TrajectoryOptions& options,
const cartographer_generic_msgs::SensorTopics& topics);
int AddTrajectory(const TrajectoryOptions& options,
const cartographer_generic_msgs::SensorTopics& topics);
void AddExtrapolator(int trajectory_id, const TrajectoryOptions& options);
// void PublishSubmapList(const ::ros::WallTimerEvent& timer_event);
// ::cartographer::mapping::PoseExtrapolator* GetExtrapolator(int trajectory_id);
// void PublishTrajectoryNodeList(const ::ros::WallTimerEvent& timer_event);
// void PublishConstraintList(const ::ros::WallTimerEvent& timer_event);
const NodeOptions node_options_;
cartographer::common::Mutex mutex_;
MapBuilderBridge map_builder_bridge_ GUARDED_BY(mutex_);
//TODO Our outputs
// ::ros::Publisher submap_list_publisher_;
// ::ros::Publisher trajectory_node_list_publisher_;
// ::ros::Publisher constraint_list_publisher_;
// ::ros::Publisher scan_matched_point_cloud_publisher_;
// These are keyed with 'trajectory_id'.
std::map<int, ::cartographer::mapping::PoseExtrapolator> extrapolators_;
//std::unordered_map<int, std::vector<::ros::Subscriber>> subscribers_;
//std::unordered_set<std::string> subscribed_topics_;
std::unordered_map<int, bool> is_active_trajectory_ GUARDED_BY(mutex_);
// We have to keep the timer handles of ::ros::WallTimers around, otherwise
// they do not fire. TODO TO PUBLISH MSGS
//std::vector<::ros::WallTimer> wall_timers_;
};
} // namespace cartographer_generic
#endif // CARTOGRAPHER_GENERIC_NODE_H_
|
GMahmoud/cartographer_android
|
src/cartographer_generic/trajectory_options.h
|
<gh_stars>1-10
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_GENERIC_TRAJECTORY_OPTIONS_H_
#define CARTOGRAPHER_GENERIC_TRAJECTORY_OPTIONS_H_
#include <string>
#include "cartographer/common/lua_parameter_dictionary.h"
#include "cartographer/common/port.h"
#include "cartographer_generic/sensor_bridge.h"
namespace cartographer_generic {
struct TrajectoryOptions {
::cartographer::mapping::proto::TrajectoryBuilderOptions
trajectory_builder_options;
std::string tracking_frame;
std::string published_frame;
std::string odom_frame;
bool provide_odom_frame;
bool use_odometry;
int num_laser_scans;
int num_multi_echo_laser_scans;
int num_subdivisions_per_laser_scan;
int num_point_clouds;
};
TrajectoryOptions CreateTrajectoryOptions(
::cartographer::common::LuaParameterDictionary* lua_parameter_dictionary);
} // namespace cartographer_generic
#endif // CARTOGRAPHER_GENERIC_TRAJECTORY_OPTIONS_H_
|
GMahmoud/cartographer_android
|
src/cartographer_generic_msgs/PointCloud2Iterator.h
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Open Source Robotics Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Open Source Robotics Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CARTOGRAPHER_GENERIC_MSGS_POINTCLOUD2ITERATOR_H
#define CARTOGRAPHER_GENERIC_MSGS_POINTCLOUD2ITERATOR_H
#include "cartographer_generic_msgs/PointCloud2.h"
#include <string>
#include <vector>
namespace cartographer_generic_msgs
{
namespace impl
{
template<typename T, typename TT, typename U, typename C, template <typename> class V>
class PointCloud2IteratorBase
{
public:
PointCloud2IteratorBase();
PointCloud2IteratorBase(C &cloud_msg, const std::string &field_name);
V<T>& operator =(const V<T>& iter);
TT& operator [](size_t i) const;
TT& operator *() const;
V<T>& operator ++();
V<T> operator +(int i);
V<T>& operator +=(int i);
bool operator !=(const V<T>& iter) const;
V<T> end() const;
private:
int set_field(const PointCloud2 &cloud_msg, const std::string &field_name);
int point_step_;
U* data_char_;
TT* data_;
TT* data_end_;
bool is_bigendian_;
};
} // namespace impl
template<typename T>
class PointCloud2Iterator : public impl::PointCloud2IteratorBase<T, T, unsigned char, PointCloud2, PointCloud2Iterator>
{
public:
PointCloud2Iterator(PointCloud2 &cloud_msg, const std::string &field_name) :
impl::PointCloud2IteratorBase<T, T, unsigned char, PointCloud2, PointCloud2Iterator>::PointCloud2IteratorBase(cloud_msg, field_name) {}
};
} // namespace cartographer_generic_msgs
#include "cartographer_generic_msgs/impl/PointCloud2Iterator.h"
#endif // CARTOGRAPHER_GENERIC_MSGS_POINTCLOUD2ITERATOR_H
|
GMahmoud/cartographer_android
|
src/cartographer/mapping_3d/local_trajectory_builder.h
|
<reponame>GMahmoud/cartographer_android
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_MAPPING_3D_LOCAL_TRAJECTORY_BUILDER_H_
#define CARTOGRAPHER_MAPPING_3D_LOCAL_TRAJECTORY_BUILDER_H_
#include <memory>
#include "cartographer/common/time.h"
#include "cartographer/mapping/global_trajectory_builder_interface.h"
#include "cartographer/mapping/imu_tracker.h"
#include "cartographer/mapping/odometry_state_tracker.h"
#include "cartographer/mapping_3d/motion_filter.h"
#include "cartographer/mapping_3d/proto/local_trajectory_builder_options.pb.h"
#include "cartographer/mapping_3d/scan_matching/ceres_scan_matcher.h"
#include "cartographer/mapping_3d/scan_matching/real_time_correlative_scan_matcher.h"
#include "cartographer/mapping_3d/submaps.h"
#include "cartographer/sensor/range_data.h"
#include "cartographer/sensor/voxel_filter.h"
#include "cartographer/transform/rigid_transform.h"
namespace cartographer {
namespace mapping_3d {
// Wires up the local SLAM stack (i.e. UKF, scan matching, etc.) without loop
// closure.
class LocalTrajectoryBuilder {
public:
using PoseEstimate = mapping::GlobalTrajectoryBuilderInterface::PoseEstimate;
struct InsertionResult {
common::Time time;
sensor::RangeData range_data_in_tracking;
transform::Rigid3d pose_observation;
std::vector<std::shared_ptr<const Submap>> insertion_submaps;
};
explicit LocalTrajectoryBuilder(
const proto::LocalTrajectoryBuilderOptions& options);
~LocalTrajectoryBuilder();
LocalTrajectoryBuilder(const LocalTrajectoryBuilder&) = delete;
LocalTrajectoryBuilder& operator=(const LocalTrajectoryBuilder&) = delete;
void AddImuData(common::Time time, const Eigen::Vector3d& linear_acceleration,
const Eigen::Vector3d& angular_velocity);
std::unique_ptr<InsertionResult> AddRangefinderData(
common::Time time, const Eigen::Vector3f& origin,
const sensor::PointCloud& ranges);
void AddOdometerData(common::Time time,
const transform::Rigid3d& odometer_pose);
const PoseEstimate& pose_estimate() const;
private:
void Predict(common::Time time);
std::unique_ptr<InsertionResult> AddAccumulatedRangeData(
common::Time time, const sensor::RangeData& range_data_in_tracking);
std::unique_ptr<InsertionResult> InsertIntoSubmap(
common::Time time, const sensor::RangeData& range_data_in_tracking,
const transform::Rigid3d& pose_observation);
const proto::LocalTrajectoryBuilderOptions options_;
ActiveSubmaps active_submaps_;
PoseEstimate last_pose_estimate_;
MotionFilter motion_filter_;
std::unique_ptr<scan_matching::RealTimeCorrelativeScanMatcher>
real_time_correlative_scan_matcher_;
std::unique_ptr<scan_matching::CeresScanMatcher> ceres_scan_matcher_;
// Current 'pose_estimate_' and 'velocity_estimate_' at 'time_'.
common::Time time_ = common::Time::min();
transform::Rigid3d pose_estimate_ = transform::Rigid3d::Identity();
Eigen::Vector3d velocity_estimate_ = Eigen::Vector3d::Zero();
common::Time last_scan_match_time_ = common::Time::min();
// This is the difference between the model (constant velocity, IMU)
// prediction 'pose_estimate_' and the odometry prediction. To get the
// odometry prediction, right-multiply this to 'pose_estimate_'.
transform::Rigid3d odometry_correction_ = transform::Rigid3d::Identity();
std::unique_ptr<mapping::ImuTracker> imu_tracker_;
mapping::OdometryStateTracker odometry_state_tracker_;
int num_accumulated_ = 0;
transform::Rigid3f first_pose_estimate_ = transform::Rigid3f::Identity();
sensor::RangeData accumulated_range_data_;
};
} // namespace mapping_3d
} // namespace cartographer
#endif // CARTOGRAPHER_MAPPING_3D_LOCAL_TRAJECTORY_BUILDER_H_
|
GMahmoud/cartographer_android
|
src/cartographer_generic/msg_conversion.h
|
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_GENERIC_MSG_CONVERSION_H_
#define CARTOGRAPHER_GENERIC_MSG_CONVERSION_H_
#include "cartographer/common/port.h"
#include "cartographer/sensor/point_cloud.h"
#include "cartographer/transform/rigid_transform.h"
#include "cartographer_generic_msgs/Pose.h"
#include "cartographer_generic_msgs/LaserScan.h"
#include "cartographer_generic_msgs/Vector3.h"
namespace cartographer_generic {
//cartographer_generic_msgs::PointCloud2 ToPointCloud2Message(
// int64 timestamp, const string& frame_id,
// const ::cartographer::sensor::PointCloud& point_cloud);
//cartographer_generic_msgs::Transform ToGeometryMsgTransform(
// const ::cartographer::transform::Rigid3d& rigid3d);
cartographer_generic_msgs::Pose ToGeometryMsgPose(
const ::cartographer::transform::Rigid3d& rigid3d);
cartographer_generic_msgs::Point ToGeometryMsgPoint(const Eigen::Vector3d& vector3d);
::cartographer::sensor::PointCloudWithIntensities ToPointCloudWithIntensities(
const cartographer_generic_msgs::LaserScan& msg);
//::cartographer::sensor::PointCloudWithIntensities ToPointCloudWithIntensities(
// const cartographer_generic_msgs::MultiEchoLaserScan& msg);
//::cartographer::sensor::PointCloudWithIntensities ToPointCloudWithIntensities(
// const cartographer_generic_msgs::PointCloud2& message);
//::cartographer::transform::Rigid3d ToRigid3d(
// const cartographer_generic_msgs::TransformStamped& transform);
::cartographer::transform::Rigid3d ToRigid3d(const cartographer_generic_msgs::Pose& pose);
Eigen::Vector3d ToEigen(const cartographer_generic_msgs::Vector3& vector3);
Eigen::Quaterniond ToEigen(const cartographer_generic_msgs::Quaternion& quaternion);
} // namespace cartographer_generic
#endif // CARTOGRAPHER_GENERIC_MSG_CONVERSION_H_
|
heaven-hq/minizip
|
minizip.c
|
<reponame>heaven-hq/minizip
/* minizip.c
Version 2.9.2, February 12, 2020
part of the MiniZip project
Copyright (C) 2010-2020 <NAME>
https://github.com/nmoinvaz/minizip
Copyright (C) 1998-2010 <NAME>
https://www.winimage.com/zLibDll/minizip.html
This program is distributed under the terms of the same license as zlib.
See the accompanying LICENSE file for the full text of the license.
*/
#include "mz.h"
#include "mz_os.h"
#include "mz_strm.h"
#include "mz_strm_buf.h"
#include "mz_strm_split.h"
#include "mz_zip.h"
#include "mz_zip_rw.h"
#include <stdio.h> /* printf */
/***************************************************************************/
typedef struct minizip_opt_s {
uint8_t include_path;
int16_t compress_level;
uint8_t compress_method;
uint8_t overwrite;
uint8_t append;
int64_t disk_size;
uint8_t follow_links;
uint8_t store_links;
uint8_t zip_cd;
int32_t encoding;
uint8_t verbose;
uint8_t aes;
const char *cert_path;
const char *cert_pwd;
} minizip_opt;
/***************************************************************************/
int32_t minizip_banner(void);
int32_t minizip_help(void);
int32_t minizip_list(const char *path);
int32_t minizip_add_entry_cb(void *handle, void *userdata, mz_zip_file *file_info);
int32_t minizip_add_progress_cb(void *handle, void *userdata, mz_zip_file *file_info, int64_t position);
int32_t minizip_add_overwrite_cb(void *handle, void *userdata, const char *path);
int32_t minizip_add(const char *path, const char *password, minizip_opt *options, int32_t arg_count, const char **args);
int32_t minizip_extract_entry_cb(void *handle, void *userdata, mz_zip_file *file_info, const char *path);
int32_t minizip_extract_progress_cb(void *handle, void *userdata, mz_zip_file *file_info, int64_t position);
int32_t minizip_extract_overwrite_cb(void *handle, void *userdata, mz_zip_file *file_info, const char *path);
int32_t minizip_extract(const char *path, const char *pattern, const char *destination, const char *password, minizip_opt *options);
int32_t minizip_erase(const char *src_path, const char *target_path, int32_t arg_count, const char **args);
/***************************************************************************/
int32_t minizip_banner(void)
{
printf("Minizip %s - https://github.com/nmoinvaz/minizip\n", MZ_VERSION);
printf("---------------------------------------------------\n");
return MZ_OK;
}
int32_t minizip_help(void)
{
printf("Usage: minizip [-x][-d dir|-l|-e][-o][-f][-y][-c cp][-a][-j][-0 to -9][-b|-m][-k 512][-p pwd][-s] file.zip [files]\n\n" \
" -x Extract files\n" \
" -l List files\n" \
" -d Destination directory\n" \
" -o Overwrite existing files\n" \
" -c File names use cp437 encoding (or specified codepage)\n" \
" -a Append to existing zip file\n" \
" -i Include full path of files\n" \
" -f Follow symbolic links\n" \
" -y Store symbolic links\n" \
" -v Verbose info\n" \
" -0 Store only\n" \
" -1 Compress faster\n" \
" -9 Compress better\n" \
" -k Disk size in KB\n" \
" -z Zip central directory\n" \
" -p Encryption password\n" \
" -s AES encryption\n" \
" -h PKCS12 certificate path\n" \
" -w PKCS12 certificate password\n" \
" -b BZIP2 compression\n" \
" -m LZMA compression\n\n");
return MZ_OK;
}
/***************************************************************************/
int32_t minizip_list(const char *path)
{
mz_zip_file *file_info = NULL;
uint32_t ratio = 0;
int16_t level = 0;
int32_t err = MZ_OK;
struct tm tmu_date;
const char *string_method = NULL;
char crypt = ' ';
void *reader = NULL;
mz_zip_reader_create(&reader);
err = mz_zip_reader_open_file(reader, path);
if (err != MZ_OK)
{
printf("Error %" PRId32 " opening archive %s\n", err, path);
mz_zip_reader_delete(&reader);
return err;
}
err = mz_zip_reader_goto_first_entry(reader);
if (err != MZ_OK && err != MZ_END_OF_LIST)
{
printf("Error %" PRId32 " going to first entry in archive\n", err);
mz_zip_reader_delete(&reader);
return err;
}
printf(" Packed Unpacked Ratio Method Attribs Date Time CRC-32 Name\n");
printf(" ------ -------- ----- ------ ------- ---- ---- ------ ----\n");
/* Enumerate all entries in the archive */
do
{
err = mz_zip_reader_entry_get_info(reader, &file_info);
if (err != MZ_OK)
{
printf("Error %" PRId32 " getting entry info in archive\n", err);
break;
}
ratio = 0;
if (file_info->uncompressed_size > 0)
ratio = (uint32_t)((file_info->compressed_size * 100) / file_info->uncompressed_size);
/* Display a '*' if the file is encrypted */
if (file_info->flag & MZ_ZIP_FLAG_ENCRYPTED)
crypt = '*';
else
crypt = ' ';
switch (file_info->compression_method)
{
case MZ_COMPRESS_METHOD_STORE:
string_method = "Stored";
break;
case MZ_COMPRESS_METHOD_DEFLATE:
level = (int16_t)((file_info->flag & 0x6) / 2);
if (level == 0)
string_method = "Defl:N";
else if (level == 1)
string_method = "Defl:X";
else if ((level == 2) || (level == 3))
string_method = "Defl:F"; /* 2: fast , 3: extra fast */
else
string_method = "Defl:?";
break;
case MZ_COMPRESS_METHOD_BZIP2:
string_method = "BZip2";
break;
case MZ_COMPRESS_METHOD_LZMA:
string_method = "LZMA";
break;
default:
string_method = "?";
}
mz_zip_time_t_to_tm(file_info->modified_date, &tmu_date);
/* Print entry information */
printf("%12" PRId64 " %12" PRId64 " %3" PRIu32 "%% %6s%c %8" PRIx32 " %2.2" PRIu32 \
"-%2.2" PRIu32 "-%2.2" PRIu32 " %2.2" PRIu32 ":%2.2" PRIu32 " %8.8" PRIx32 " %s\n",
file_info->compressed_size, file_info->uncompressed_size, ratio,
string_method, crypt, file_info->external_fa,
(uint32_t)tmu_date.tm_mon + 1, (uint32_t)tmu_date.tm_mday,
(uint32_t)tmu_date.tm_year % 100,
(uint32_t)tmu_date.tm_hour, (uint32_t)tmu_date.tm_min,
file_info->crc, file_info->filename);
err = mz_zip_reader_goto_next_entry(reader);
if (err != MZ_OK && err != MZ_END_OF_LIST)
{
printf("Error %" PRId32 " going to next entry in archive\n", err);
break;
}
}
while (err == MZ_OK);
mz_zip_reader_delete(&reader);
if (err == MZ_END_OF_LIST)
return MZ_OK;
return err;
}
/***************************************************************************/
int32_t minizip_add_entry_cb(void *handle, void *userdata, mz_zip_file *file_info)
{
MZ_UNUSED(handle);
MZ_UNUSED(userdata);
/* Print the current file we are trying to compress */
printf("Adding %s\n", file_info->filename);
return MZ_OK;
}
int32_t minizip_add_progress_cb(void *handle, void *userdata, mz_zip_file *file_info, int64_t position)
{
minizip_opt *options = (minizip_opt *)userdata;
double progress = 0;
uint8_t raw = 0;
MZ_UNUSED(userdata);
mz_zip_writer_get_raw(handle, &raw);
if (raw && file_info->compressed_size > 0)
progress = ((double)position / file_info->compressed_size) * 100;
else if (!raw && file_info->uncompressed_size > 0)
progress = ((double)position / file_info->uncompressed_size) * 100;
/* Print the progress of the current compress operation */
if (options->verbose)
printf("%s - %" PRId64 " / %" PRId64 " (%.02f%%)\n", file_info->filename, position,
file_info->uncompressed_size, progress);
return MZ_OK;
}
int32_t minizip_add_overwrite_cb(void *handle, void *userdata, const char *path)
{
minizip_opt *options = (minizip_opt *)userdata;
MZ_UNUSED(handle);
if (options->overwrite == 0)
{
/* If ask the user what to do because append and overwrite args not set */
char rep = 0;
do
{
char answer[128];
printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ", path);
if (scanf("%1s", answer) != 1)
exit(EXIT_FAILURE);
rep = answer[0];
if ((rep >= 'a') && (rep <= 'z'))
rep -= 0x20;
}
while ((rep != 'Y') && (rep != 'N') && (rep != 'A'));
if (rep == 'A')
{
return MZ_EXIST_ERROR;
}
else if (rep == 'N')
{
return MZ_INTERNAL_ERROR;
}
}
return MZ_OK;
}
#include "mz_compat.h"
zipFile _zip;
//add
int32_t writeFileAtPath(const char *fileName, const char *password, minizip_opt *options)
{
int32_t err = MZ_OK;
FILE *input = fopen(fileName, "r");
if (NULL == input) {
return -1;
}
printf("=============\n");
//if (!fileName) {
// fileName = path.lastPathComponent;
//}
zip_fileinfo zipInfo = {0};
//[SSZipArchive zipInfo : &zipInfo setAttributesOfItemAtPath : path];
void *buffer = malloc(16384);
if (buffer == NULL)
{
fclose(input);
return -1;
}
//int error = _zipOpenEntry(_zip, fileName, &zipInfo, compressionLevel, password, aes);
zipOpenNewFileInZip5(_zip, fileName, &zipInfo, NULL, 0, NULL, 0, NULL, 0, 0, 0, 0, 0, 0, password, NULL, 0, 0, 0);
if (mz_os_is_symlink(fileName) == MZ_OK)
{
char link_path[1024];
err = mz_os_read_symlink(fileName, link_path, sizeof(link_path));
if (err == MZ_OK)
zipWriteInFileInZip(_zip, link_path, sizeof(link_path));
} else {
while (!feof(input) && !ferror(input))
{
unsigned int len = (unsigned int)fread(buffer, 1, 16384, input);
zipWriteInFileInZip(_zip, buffer, len);
}
}
zipCloseFileInZip(_zip);
free(buffer);
fclose(input);
return 0;
}
//add
int32_t writeFolderAtPath(char *fileName, const char *passord, nimizip_opt *options)
{
DIR *dir = NULL;
struct dirent *entry = NULL;
int32_t err = MZ_OK;
int16_t is_dir = 0;
const char *filename = NULL;
const char *filenameinzip = fileName;
char *wildcard_ptr = NULL;
char full_path[1024];
char path_dir[1024];
if (mz_os_is_dir(fileName) == MZ_OK)
is_dir = 1;
if (!is_dir)
{
err = writeFileAtPath(fileName, NULL, 0);
return err;
} else {
dir = mz_os_open_dir(fileName);
if (dir == NULL)
return MZ_EXIST_ERROR;
while ((entry = mz_os_read_dir(dir)) != NULL)
{
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
full_path[0] = 0;
mz_path_combine(full_path, fileName, sizeof(full_path));
mz_path_combine(full_path, entry->d_name, sizeof(full_path));
err = writeFolderAtPath(full_path, NULL, 0);
if (err != MZ_OK)
return err;
}
}
mz_os_close_dir(dir);
return MZ_OK;
}
int32_t minizip_add(const char *path, const char *password, minizip_opt *options, int32_t arg_count, const char **args)
{
void *writer = NULL;
int32_t err = MZ_OK;
int32_t err_close = MZ_OK;
int32_t i = 0;
int16_t is_dir = 0;
const char *filename_in_zip = NULL;
printf("Archive %s\n", path);
_zip = zipOpen(path, APPEND_STATUS_CREATE);
if(!_zip)
{
printf("zipOpen Error\n");
return -1;
}
for (i = 0; i < arg_count; i += 1)
{
filename_in_zip = args[i];
printf("args[%d]:%s\n",i,filename_in_zip);
//is_dir
if (mz_os_is_dir(filename_in_zip) == MZ_OK)
is_dir = 1;
if (!is_dir)
{
/* Add file system path to archive */
err = writeFileAtPath(filename_in_zip, NULL, options->include_path);
} else {
err = writeFolderAtPath(filename_in_zip, NULL, 0);
}
if (err != MZ_OK)
printf("Error %" PRId32 " adding path to archive %s\n", err, filename_in_zip);
zipClose(_zip, NULL);
return err;
}
//int32_t minizip_add(const char *path, const char *password, minizip_opt *options, int32_t arg_count, const char **args)
//{
// void *writer = NULL;
// int32_t err = MZ_OK;
// int32_t err_close = MZ_OK;
// int32_t i = 0;
// const char *filename_in_zip = NULL;
//
//
// printf("Archive %s\n", path);
//
// /* Create zip writer */
// mz_zip_writer_create(&writer);
// mz_zip_writer_set_password(writer, password);
// mz_zip_writer_set_compress_method(writer, options->compress_method);
// mz_zip_writer_set_compress_level(writer, options->compress_level);
// mz_zip_writer_set_follow_links(writer, options->follow_links);
// mz_zip_writer_set_store_links(writer, options->store_links);
// mz_zip_writer_set_overwrite_cb(writer, options, minizip_add_overwrite_cb);
// mz_zip_writer_set_progress_cb(writer, options, minizip_add_progress_cb);
// mz_zip_writer_set_entry_cb(writer, options, minizip_add_entry_cb);
// mz_zip_writer_set_zip_cd(writer, options->zip_cd);
// if (options->cert_path != NULL)
// mz_zip_writer_set_certificate(writer, options->cert_path, options->cert_pwd);
//
// err = mz_zip_writer_open_file(writer, path, options->disk_size, options->append);
//
// if (err == MZ_OK)
// {
// for (i = 0; i < arg_count; i += 1)
// {
// filename_in_zip = args[i];
//
// /* Add file system path to archive */
// err = mz_zip_writer_add_path(writer, filename_in_zip, NULL, options->include_path, 1);
// if (err != MZ_OK)
// printf("Error %" PRId32 " adding path to archive %s\n", err, filename_in_zip);
// }
// }
// else
// {
// printf("Error %" PRId32 " opening archive for writing\n", err);
// }
//
// err_close = mz_zip_writer_close(writer);
// if (err_close != MZ_OK)
// {
// printf("Error %" PRId32 " closing archive for writing %s\n", err_close, path);
// err = err_close;
// }
//
// mz_zip_writer_delete(&writer);
// return err;
//}
/***************************************************************************/
int32_t minizip_extract_entry_cb(void *handle, void *userdata, mz_zip_file *file_info, const char *path)
{
MZ_UNUSED(handle);
MZ_UNUSED(userdata);
MZ_UNUSED(path);
/* Print the current entry extracting */
printf("Extracting %s\n", file_info->filename);
return MZ_OK;
}
int32_t minizip_extract_progress_cb(void *handle, void *userdata, mz_zip_file *file_info, int64_t position)
{
minizip_opt *options = (minizip_opt *)userdata;
double progress = 0;
uint8_t raw = 0;
MZ_UNUSED(userdata);
mz_zip_reader_get_raw(handle, &raw);
if (raw && file_info->compressed_size > 0)
progress = ((double)position / file_info->compressed_size) * 100;
else if (!raw && file_info->uncompressed_size > 0)
progress = ((double)position / file_info->uncompressed_size) * 100;
/* Print the progress of the current extraction */
if (options->verbose)
printf("%s - %" PRId64 " / %" PRId64 " (%.02f%%)\n", file_info->filename, position,
file_info->uncompressed_size, progress);
return MZ_OK;
}
int32_t minizip_extract_overwrite_cb(void *handle, void *userdata, mz_zip_file *file_info, const char *path)
{
minizip_opt *options = (minizip_opt *)userdata;
MZ_UNUSED(handle);
MZ_UNUSED(file_info);
/* Verify if we want to overwrite current entry on disk */
if (options->overwrite == 0)
{
char rep = 0;
do
{
char answer[128];
printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ", path);
if (scanf("%1s", answer) != 1)
exit(EXIT_FAILURE);
rep = answer[0];
if ((rep >= 'a') && (rep <= 'z'))
rep -= 0x20;
} while ((rep != 'Y') && (rep != 'N') && (rep != 'A'));
if (rep == 'N')
return MZ_EXIST_ERROR;
if (rep == 'A')
options->overwrite = 1;
}
return MZ_OK;
}
int32_t minizip_extract(const char *path, const char *pattern, const char *destination, const char *password, minizip_opt *options)
{
void *reader = NULL;
int32_t err = MZ_OK;
int32_t err_close = MZ_OK;
printf("Archive %s\n", path);
/* Create zip reader */
mz_zip_reader_create(&reader);
mz_zip_reader_set_pattern(reader, pattern, 1);
mz_zip_reader_set_password(reader, password);
mz_zip_reader_set_encoding(reader, options->encoding);
mz_zip_reader_set_entry_cb(reader, options, minizip_extract_entry_cb);
mz_zip_reader_set_progress_cb(reader, options, minizip_extract_progress_cb);
mz_zip_reader_set_overwrite_cb(reader, options, minizip_extract_overwrite_cb);
err = mz_zip_reader_open_file(reader, path);
if (err != MZ_OK)
{
printf("Error %" PRId32 " opening archive %s\n", err, path);
}
else
{
/* Save all entries in archive to destination directory */
err = mz_zip_reader_save_all(reader, destination);
if (err == MZ_END_OF_LIST)
{
if (pattern != NULL)
{
printf("Files matching %s not found in archive\n", pattern);
}
else
{
printf("No files in archive\n");
err = MZ_OK;
}
}
else if (err != MZ_OK)
{
printf("Error %" PRId32 " saving entries to disk %s\n", err, path);
}
}
err_close = mz_zip_reader_close(reader);
if (err_close != MZ_OK)
{
printf("Error %" PRId32 " closing archive for reading\n", err_close);
err = err_close;
}
mz_zip_reader_delete(&reader);
return err;
}
/***************************************************************************/
int32_t minizip_erase(const char *src_path, const char *target_path, int32_t arg_count, const char **args)
{
mz_zip_file *file_info = NULL;
const char *filename_in_zip = NULL;
const char *target_path_ptr = target_path;
void *reader = NULL;
void *writer = NULL;
int32_t skip = 0;
int32_t err = MZ_OK;
int32_t i = 0;
uint8_t zip_cd = 0;
char bak_path[256];
char tmp_path[256];
if (target_path == NULL)
{
/* Construct temporary zip name */
strncpy(tmp_path, src_path, sizeof(tmp_path) - 1);
tmp_path[sizeof(tmp_path) - 1] = 0;
strncat(tmp_path, ".tmp.zip", sizeof(tmp_path) - strlen(tmp_path) - 1);
target_path_ptr = tmp_path;
}
mz_zip_reader_create(&reader);
mz_zip_writer_create(&writer);
/* Open original archive we want to erase an entry in */
err = mz_zip_reader_open_file(reader, src_path);
if (err != MZ_OK)
{
printf("Error %" PRId32 " opening archive for reading %s\n", err, src_path);
mz_zip_reader_delete(&reader);
return err;
}
/* Open temporary archive */
err = mz_zip_writer_open_file(writer, target_path_ptr, 0, 0);
if (err != MZ_OK)
{
printf("Error %" PRId32 " opening archive for writing %s\n", err, target_path_ptr);
mz_zip_reader_delete(&reader);
mz_zip_writer_delete(&writer);
return err;
}
err = mz_zip_reader_goto_first_entry(reader);
if (err != MZ_OK && err != MZ_END_OF_LIST)
printf("Error %" PRId32 " going to first entry in archive\n", err);
while (err == MZ_OK)
{
err = mz_zip_reader_entry_get_info(reader, &file_info);
if (err != MZ_OK)
{
printf("Error %" PRId32 " getting info from archive\n", err);
break;
}
/* Copy all entries from original archive to temporary archive
except the ones we don't want */
for (i = 0, skip = 0; i < arg_count; i += 1)
{
filename_in_zip = args[i];
if (mz_path_compare_wc(file_info->filename, filename_in_zip, 1) == MZ_OK)
skip = 1;
}
if (skip)
{
printf("Skipping %s\n", file_info->filename);
}
else
{
printf("Copying %s\n", file_info->filename);
err = mz_zip_writer_copy_from_reader(writer, reader);
}
if (err != MZ_OK)
{
printf("Error %" PRId32 " copying entry into new zip\n", err);
break;
}
err = mz_zip_reader_goto_next_entry(reader);
if (err != MZ_OK && err != MZ_END_OF_LIST)
printf("Error %" PRId32 " going to next entry in archive\n", err);
}
mz_zip_reader_get_zip_cd(reader, &zip_cd);
mz_zip_writer_set_zip_cd(writer, zip_cd);
mz_zip_reader_close(reader);
mz_zip_reader_delete(&reader);
mz_zip_writer_close(writer);
mz_zip_writer_delete(&writer);
if (err == MZ_END_OF_LIST)
{
if (target_path == NULL)
{
/* Swap original archive with temporary archive, backup old archive if possible */
strncpy(bak_path, src_path, sizeof(bak_path) - 1);
bak_path[sizeof(bak_path) - 1] = 0;
strncat(bak_path, ".bak", sizeof(bak_path) - strlen(bak_path) - 1);
if (mz_os_file_exists(bak_path) == MZ_OK)
mz_os_unlink(bak_path);
if (mz_os_rename(src_path, bak_path) != MZ_OK)
printf("Error backing up archive before replacing %s\n", bak_path);
if (mz_os_rename(tmp_path, src_path) != MZ_OK)
printf("Error replacing archive with temp %s\n", tmp_path);
}
return MZ_OK;
}
return err;
}
/***************************************************************************/
#if !defined(MZ_ZIP_NO_MAIN)
int main(int argc, const char *argv[])
{
minizip_opt options;
int32_t path_arg = 0;
int32_t err = 0;
int32_t i = 0;
uint8_t do_list = 0;
uint8_t do_extract = 0;
uint8_t do_erase = 0;
const char *path = NULL;
const char *password = NULL;
const char *destination = NULL;
const char *filename_to_extract = NULL;
minizip_banner();
if (argc == 1)
{
minizip_help();
return 0;
}
memset(&options, 0, sizeof(options));
options.compress_method = MZ_COMPRESS_METHOD_DEFLATE;
options.compress_level = MZ_COMPRESS_LEVEL_DEFAULT;
/* Parse command line options */
for (i = 1; i < argc; i += 1)
{
printf("%s ", argv[i]);
if (argv[i][0] == '-')
{
char c = argv[i][1];
if ((c == 'l') || (c == 'L'))
do_list = 1;
else if ((c == 'x') || (c == 'X'))
do_extract = 1;
else if ((c == 'e') || (c == 'E'))
do_erase = 1;
else if ((c == 'a') || (c == 'A'))
options.append = 1;
else if ((c == 'o') || (c == 'O'))
options.overwrite = 1;
else if ((c == 'f') || (c == 'F'))
options.follow_links = 1;
else if ((c == 'y') || (c == 'Y'))
options.store_links = 1;
else if ((c == 'i') || (c == 'I'))
options.include_path = 1;
else if ((c == 'z') || (c == 'Z'))
options.zip_cd = 1;
else if ((c == 'v') || (c == 'V'))
options.verbose = 1;
else if ((c >= '0') && (c <= '9'))
{
options.compress_level = (c - '0');
if (options.compress_level == 0)
options.compress_method = MZ_COMPRESS_METHOD_STORE;
}
else if ((c == 'b') || (c == 'B'))
#ifdef HAVE_BZIP2
options.compress_method = MZ_COMPRESS_METHOD_BZIP2;
#else
err = MZ_SUPPORT_ERROR;
#endif
else if ((c == 'm') || (c == 'M'))
#ifdef HAVE_LZMA
options.compress_method = MZ_COMPRESS_METHOD_LZMA;
#else
err = MZ_SUPPORT_ERROR;
#endif
else if ((c == 's') || (c == 'S'))
#ifdef HAVE_WZAES
options.aes = 1;
#else
err = MZ_SUPPORT_ERROR;
#endif
else if (((c == 'h') || (c == 'H')) && (i + 1 < argc))
{
#ifdef MZ_ZIP_SIGNING
options.cert_path = argv[i + 1];
printf("%s ", argv[i + 1]);
#else
err = MZ_SUPPORT_ERROR;
#endif
i += 1;
}
else if (((c == 'w') || (c == 'W')) && (i + 1 < argc))
{
#ifdef MZ_ZIP_SIGNING
options.cert_pwd = argv[i + 1];
printf("%s ", argv[i + 1]);
#else
err = MZ_SUPPORT_ERROR;
#endif
i += 1;
}
else if (((c == 'c') || (c == 'C')) && (i + 1 < argc))
{
options.encoding = (int32_t)atoi(argv[i + 1]);
i += 1;
}
else if (((c == 'k') || (c == 'K')) && (i + 1 < argc))
{
options.disk_size = (int64_t)atoi(argv[i + 1]) * 1024;
printf("%s ", argv[i + 1]);
i += 1;
}
else if (((c == 'd') || (c == 'D')) && (i + 1 < argc))
{
destination = argv[i + 1];
printf("%s ", argv[i + 1]);
i += 1;
}
else if (((c == 'p') || (c == 'P')) && (i + 1 < argc))
{
#ifndef MZ_ZIP_NO_ENCRYPTION
password = argv[i + 1];
printf("*** ");
#else
err = MZ_SUPPORT_ERROR;
#endif
i += 1;
}
}
else if (path_arg == 0)
path_arg = i;
}
printf("\n");
if (err == MZ_SUPPORT_ERROR)
{
printf("Feature not supported\n");
return err;
}
if (path_arg == 0)
{
minizip_help();
return 0;
}
path = argv[path_arg];
if (do_list)
{
/* List archive contents */
err = minizip_list(path);
}
else if (do_extract)
{
if (argc > path_arg + 1)
filename_to_extract = argv[path_arg + 1];
/* Extract archive */
err = minizip_extract(path, filename_to_extract, destination, password, &options);
}
else if (do_erase)
{
/* Erase file in archive */
err = minizip_erase(path, NULL, argc - (path_arg + 1), &argv[path_arg + 1]);
}
else
{
/* Add files to archive */
err = minizip_add(path, password, &options, argc - (path_arg + 1), &argv[path_arg + 1]);
}
return err;
}
#endif
|
kenoph/miasm-stuff
|
tutorial/simplevm/vm.c
|
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
enum Opcode {
EXIT = 0,
ADDI,
GETC,
HASH,
JNZ,
PUTC,
SUBM,
};
typedef struct Instruction_t {
int opcode;
int arg0;
int arg1;
int arg2;
} Instruction;
#define MEM_SIZE 0x100
#define ADDR_STR 0x00
#define REG_STRLEN 0x09
#define REG_HASH (REG_STRLEN + 1)
#define REG_Z 0xFF
#define MAX_STR_LEN (REG_STRLEN - ADDR_STR - 1)
static const Instruction CODE[] = {
{PUTC, 'H', 'e', 'l'},
{PUTC, 'l', 'o', '.'},
{PUTC, '.', '.', '\n'},
{PUTC, 'P', 'l', 'e'},
{PUTC, 'a', 's', 'e'},
{PUTC, ' ', 'e', 'n'},
{PUTC, 't', 'e', 'r'},
{PUTC, ' ', 'p', 'a'},
{PUTC, 's', 's', 'w'},
{PUTC, 'o', 'r', 'd'},
{PUTC, 0, ':', '\n'},
{GETC, ADDR_STR, REG_STRLEN, 0},
{ADDI, REG_STRLEN, 1, 0},
{SUBM, REG_Z, REG_STRLEN, MAX_STR_LEN},
{JNZ, -4, 123, 666},
{PUTC, 'C', 'h', 'e'},
{PUTC, 'c', 'k', 'i'},
{PUTC, 'n', 'g', '.'},
{PUTC, '.', '.', ' '},
{HASH, ADDR_STR, REG_STRLEN, 0x666},
{ADDI, REG_STRLEN, -1, 0},
{SUBM, REG_Z, REG_STRLEN, 0},
{JNZ, -4, 0x1337, 0xB00B5},
{ADDI, REG_HASH, -0x319A, 0},
{SUBM, REG_Z, REG_HASH, 0},
{JNZ, 6, 0, 0},
{PUTC, 'F', 'l', 'a'},
{PUTC, 'g', '{', 'f'},
{PUTC, 'u', 'c', 'k'},
{PUTC, '_', '0', 'f'},
{PUTC, 'f', '}', '\n'},
{EXIT, 0, 0, 0},
{PUTC, 'W', 'r', 'o'},
{PUTC, 'n', 'g', ' '},
{PUTC, ':', '/', 0},
{PUTC, '\n', 0, 0},
};
//#define DEV
#ifdef DEV
#define DEBUG(...) fprintf(stdout, __VA_ARGS__)
#else
#define DEBUG(...)
#endif
void interpret(int ip) {
int mem[MEM_SIZE] = {0};
int code_length = sizeof(CODE) / sizeof(CODE[0]);
while (ip >= 0 && ip < code_length) {
Instruction i = CODE[ip];
int args[3] = {i.arg0, i.arg1, i.arg2};
DEBUG("\n");
for (int j=0; j<21; j++) {
DEBUG("%02X ", mem[j]);
}
DEBUG("STRLEN: %d\n", mem[REG_STRLEN]);
DEBUG("\n");
switch (i.opcode) {
case ADDI:
mem[i.arg0] += i.arg1;
break;
case GETC:
mem[i.arg0 + mem[i.arg1]] = getc(stdin);
break;
case HASH:
mem[REG_HASH] += mem[i.arg0 + mem[i.arg1]] ^ i.arg2;
break;
case JNZ:
if (mem[REG_Z]) ip += i.arg0;
break;
case PUTC:
for (int a=0; a<3; a++) { if (args[a] != 0) putc(args[a], stdout); }
break;
case SUBM:
mem[i.arg0] = mem[i.arg1] - i.arg2;
break;
case EXIT:
ip = -2;
break;
}
ip++;
}
}
int main(int argc, char *argv[]) {
interpret(0);
return 0;
}
|
ryancwicks/aravis-rs
|
aravis-sys/tests/manual.h
|
// Feel free to edit this file, it won't be regenerated by gir generator unless removed.
#include <arv.h>
#define ARV_H_INSIDE
#include <arvgcstringnode.h>
#undef ARV_H_INSIDE
|
ryancwicks/aravis-rs
|
aravis-sys/tests/layout.c
|
// Generated by gir (https://github.com/gtk-rs/gir @ e8f82cf)
// from ../gir-files (@ 6f12897)
// DO NOT EDIT
#include "manual.h"
#include <stdalign.h>
#include <stdio.h>
int main() {
printf("%s;%zu;%zu\n", "ArvAcquisitionMode", sizeof(ArvAcquisitionMode), alignof(ArvAcquisitionMode));
printf("%s;%zu;%zu\n", "ArvAuto", sizeof(ArvAuto), alignof(ArvAuto));
printf("%s;%zu;%zu\n", "ArvBufferClass", sizeof(ArvBufferClass), alignof(ArvBufferClass));
printf("%s;%zu;%zu\n", "ArvBufferPayloadType", sizeof(ArvBufferPayloadType), alignof(ArvBufferPayloadType));
printf("%s;%zu;%zu\n", "ArvBufferStatus", sizeof(ArvBufferStatus), alignof(ArvBufferStatus));
printf("%s;%zu;%zu\n", "ArvCamera", sizeof(ArvCamera), alignof(ArvCamera));
printf("%s;%zu;%zu\n", "ArvCameraClass", sizeof(ArvCameraClass), alignof(ArvCameraClass));
printf("%s;%zu;%zu\n", "ArvChunkParserClass", sizeof(ArvChunkParserClass), alignof(ArvChunkParserClass));
printf("%s;%zu;%zu\n", "ArvChunkParserError", sizeof(ArvChunkParserError), alignof(ArvChunkParserError));
printf("%s;%zu;%zu\n", "ArvDevice", sizeof(ArvDevice), alignof(ArvDevice));
printf("%s;%zu;%zu\n", "ArvDeviceClass", sizeof(ArvDeviceClass), alignof(ArvDeviceClass));
printf("%s;%zu;%zu\n", "ArvDeviceError", sizeof(ArvDeviceError), alignof(ArvDeviceError));
printf("%s;%zu;%zu\n", "ArvDomCharacterData", sizeof(ArvDomCharacterData), alignof(ArvDomCharacterData));
printf("%s;%zu;%zu\n", "ArvDomCharacterDataClass", sizeof(ArvDomCharacterDataClass), alignof(ArvDomCharacterDataClass));
printf("%s;%zu;%zu\n", "ArvDomDocument", sizeof(ArvDomDocument), alignof(ArvDomDocument));
printf("%s;%zu;%zu\n", "ArvDomDocumentClass", sizeof(ArvDomDocumentClass), alignof(ArvDomDocumentClass));
printf("%s;%zu;%zu\n", "ArvDomDocumentFragment", sizeof(ArvDomDocumentFragment), alignof(ArvDomDocumentFragment));
printf("%s;%zu;%zu\n", "ArvDomDocumentFragmentClass", sizeof(ArvDomDocumentFragmentClass), alignof(ArvDomDocumentFragmentClass));
printf("%s;%zu;%zu\n", "ArvDomElement", sizeof(ArvDomElement), alignof(ArvDomElement));
printf("%s;%zu;%zu\n", "ArvDomElementClass", sizeof(ArvDomElementClass), alignof(ArvDomElementClass));
printf("%s;%zu;%zu\n", "ArvDomNamedNodeMap", sizeof(ArvDomNamedNodeMap), alignof(ArvDomNamedNodeMap));
printf("%s;%zu;%zu\n", "ArvDomNamedNodeMapClass", sizeof(ArvDomNamedNodeMapClass), alignof(ArvDomNamedNodeMapClass));
printf("%s;%zu;%zu\n", "ArvDomNode", sizeof(ArvDomNode), alignof(ArvDomNode));
printf("%s;%zu;%zu\n", "ArvDomNodeChildListClass", sizeof(ArvDomNodeChildListClass), alignof(ArvDomNodeChildListClass));
printf("%s;%zu;%zu\n", "ArvDomNodeClass", sizeof(ArvDomNodeClass), alignof(ArvDomNodeClass));
printf("%s;%zu;%zu\n", "ArvDomNodeList", sizeof(ArvDomNodeList), alignof(ArvDomNodeList));
printf("%s;%zu;%zu\n", "ArvDomNodeListClass", sizeof(ArvDomNodeListClass), alignof(ArvDomNodeListClass));
printf("%s;%zu;%zu\n", "ArvDomNodeType", sizeof(ArvDomNodeType), alignof(ArvDomNodeType));
printf("%s;%zu;%zu\n", "ArvDomText", sizeof(ArvDomText), alignof(ArvDomText));
printf("%s;%zu;%zu\n", "ArvDomTextClass", sizeof(ArvDomTextClass), alignof(ArvDomTextClass));
printf("%s;%zu;%zu\n", "ArvEvaluatorClass", sizeof(ArvEvaluatorClass), alignof(ArvEvaluatorClass));
printf("%s;%zu;%zu\n", "ArvExposureMode", sizeof(ArvExposureMode), alignof(ArvExposureMode));
printf("%s;%zu;%zu\n", "ArvFakeCameraClass", sizeof(ArvFakeCameraClass), alignof(ArvFakeCameraClass));
printf("%s;%zu;%zu\n", "ArvFakeDeviceClass", sizeof(ArvFakeDeviceClass), alignof(ArvFakeDeviceClass));
printf("%s;%zu;%zu\n", "ArvFakeInterfaceClass", sizeof(ArvFakeInterfaceClass), alignof(ArvFakeInterfaceClass));
printf("%s;%zu;%zu\n", "ArvFakeStreamClass", sizeof(ArvFakeStreamClass), alignof(ArvFakeStreamClass));
printf("%s;%zu;%zu\n", "ArvGcAccessMode", sizeof(ArvGcAccessMode), alignof(ArvGcAccessMode));
printf("%s;%zu;%zu\n", "ArvGcBooleanClass", sizeof(ArvGcBooleanClass), alignof(ArvGcBooleanClass));
printf("%s;%zu;%zu\n", "ArvGcCachable", sizeof(ArvGcCachable), alignof(ArvGcCachable));
printf("%s;%zu;%zu\n", "ArvGcCategoryClass", sizeof(ArvGcCategoryClass), alignof(ArvGcCategoryClass));
printf("%s;%zu;%zu\n", "ArvGcClass", sizeof(ArvGcClass), alignof(ArvGcClass));
printf("%s;%zu;%zu\n", "ArvGcCommandClass", sizeof(ArvGcCommandClass), alignof(ArvGcCommandClass));
printf("%s;%zu;%zu\n", "ArvGcConverter", sizeof(ArvGcConverter), alignof(ArvGcConverter));
printf("%s;%zu;%zu\n", "ArvGcConverterClass", sizeof(ArvGcConverterClass), alignof(ArvGcConverterClass));
printf("%s;%zu;%zu\n", "ArvGcConverterNodeClass", sizeof(ArvGcConverterNodeClass), alignof(ArvGcConverterNodeClass));
printf("%s;%zu;%zu\n", "ArvGcDisplayNotation", sizeof(ArvGcDisplayNotation), alignof(ArvGcDisplayNotation));
printf("%s;%zu;%zu\n", "ArvGcEnumEntryClass", sizeof(ArvGcEnumEntryClass), alignof(ArvGcEnumEntryClass));
printf("%s;%zu;%zu\n", "ArvGcEnumerationClass", sizeof(ArvGcEnumerationClass), alignof(ArvGcEnumerationClass));
printf("%s;%zu;%zu\n", "ArvGcError", sizeof(ArvGcError), alignof(ArvGcError));
printf("%s;%zu;%zu\n", "ArvGcFeatureNode", sizeof(ArvGcFeatureNode), alignof(ArvGcFeatureNode));
printf("%s;%zu;%zu\n", "ArvGcFeatureNodeClass", sizeof(ArvGcFeatureNodeClass), alignof(ArvGcFeatureNodeClass));
printf("%s;%zu;%zu\n", "ArvGcFloatInterface", sizeof(ArvGcFloatInterface), alignof(ArvGcFloatInterface));
printf("%s;%zu;%zu\n", "ArvGcFloatNodeClass", sizeof(ArvGcFloatNodeClass), alignof(ArvGcFloatNodeClass));
printf("%s;%zu;%zu\n", "ArvGcFloatRegNode", sizeof(ArvGcFloatRegNode), alignof(ArvGcFloatRegNode));
printf("%s;%zu;%zu\n", "ArvGcFloatRegNodeClass", sizeof(ArvGcFloatRegNodeClass), alignof(ArvGcFloatRegNodeClass));
printf("%s;%zu;%zu\n", "ArvGcGroupNodeClass", sizeof(ArvGcGroupNodeClass), alignof(ArvGcGroupNodeClass));
printf("%s;%zu;%zu\n", "ArvGcIndexNodeClass", sizeof(ArvGcIndexNodeClass), alignof(ArvGcIndexNodeClass));
printf("%s;%zu;%zu\n", "ArvGcIntConverterNodeClass", sizeof(ArvGcIntConverterNodeClass), alignof(ArvGcIntConverterNodeClass));
printf("%s;%zu;%zu\n", "ArvGcIntRegNode", sizeof(ArvGcIntRegNode), alignof(ArvGcIntRegNode));
printf("%s;%zu;%zu\n", "ArvGcIntRegNodeClass", sizeof(ArvGcIntRegNodeClass), alignof(ArvGcIntRegNodeClass));
printf("%s;%zu;%zu\n", "ArvGcIntSwissKnifeNode", sizeof(ArvGcIntSwissKnifeNode), alignof(ArvGcIntSwissKnifeNode));
printf("%s;%zu;%zu\n", "ArvGcIntSwissKnifeNodeClass", sizeof(ArvGcIntSwissKnifeNodeClass), alignof(ArvGcIntSwissKnifeNodeClass));
printf("%s;%zu;%zu\n", "ArvGcIntegerInterface", sizeof(ArvGcIntegerInterface), alignof(ArvGcIntegerInterface));
printf("%s;%zu;%zu\n", "ArvGcIntegerNodeClass", sizeof(ArvGcIntegerNodeClass), alignof(ArvGcIntegerNodeClass));
printf("%s;%zu;%zu\n", "ArvGcInvalidatorNodeClass", sizeof(ArvGcInvalidatorNodeClass), alignof(ArvGcInvalidatorNodeClass));
printf("%s;%zu;%zu\n", "ArvGcIsLinear", sizeof(ArvGcIsLinear), alignof(ArvGcIsLinear));
printf("%s;%zu;%zu\n", "ArvGcMaskedIntRegNode", sizeof(ArvGcMaskedIntRegNode), alignof(ArvGcMaskedIntRegNode));
printf("%s;%zu;%zu\n", "ArvGcMaskedIntRegNodeClass", sizeof(ArvGcMaskedIntRegNodeClass), alignof(ArvGcMaskedIntRegNodeClass));
printf("%s;%zu;%zu\n", "ArvGcNameSpace", sizeof(ArvGcNameSpace), alignof(ArvGcNameSpace));
printf("%s;%zu;%zu\n", "ArvGcNode", sizeof(ArvGcNode), alignof(ArvGcNode));
printf("%s;%zu;%zu\n", "ArvGcNodeClass", sizeof(ArvGcNodeClass), alignof(ArvGcNodeClass));
printf("%s;%zu;%zu\n", "ArvGcPortClass", sizeof(ArvGcPortClass), alignof(ArvGcPortClass));
printf("%s;%zu;%zu\n", "ArvGcPropertyNode", sizeof(ArvGcPropertyNode), alignof(ArvGcPropertyNode));
printf("%s;%zu;%zu\n", "ArvGcPropertyNodeClass", sizeof(ArvGcPropertyNodeClass), alignof(ArvGcPropertyNodeClass));
printf("%s;%zu;%zu\n", "ArvGcPropertyNodeType", sizeof(ArvGcPropertyNodeType), alignof(ArvGcPropertyNodeType));
printf("%s;%zu;%zu\n", "ArvGcRegisterDescriptionNodeClass", sizeof(ArvGcRegisterDescriptionNodeClass), alignof(ArvGcRegisterDescriptionNodeClass));
printf("%s;%zu;%zu\n", "ArvGcRegisterInterface", sizeof(ArvGcRegisterInterface), alignof(ArvGcRegisterInterface));
printf("%s;%zu;%zu\n", "ArvGcRegisterNode", sizeof(ArvGcRegisterNode), alignof(ArvGcRegisterNode));
printf("%s;%zu;%zu\n", "ArvGcRegisterNodeClass", sizeof(ArvGcRegisterNodeClass), alignof(ArvGcRegisterNodeClass));
printf("%s;%zu;%zu\n", "ArvGcRepresentation", sizeof(ArvGcRepresentation), alignof(ArvGcRepresentation));
printf("%s;%zu;%zu\n", "ArvGcSelectorInterface", sizeof(ArvGcSelectorInterface), alignof(ArvGcSelectorInterface));
printf("%s;%zu;%zu\n", "ArvGcSignedness", sizeof(ArvGcSignedness), alignof(ArvGcSignedness));
printf("%s;%zu;%zu\n", "ArvGcStreamable", sizeof(ArvGcStreamable), alignof(ArvGcStreamable));
printf("%s;%zu;%zu\n", "ArvGcStringInterface", sizeof(ArvGcStringInterface), alignof(ArvGcStringInterface));
printf("%s;%zu;%zu\n", "ArvGcStringNodeClass", sizeof(ArvGcStringNodeClass), alignof(ArvGcStringNodeClass));
printf("%s;%zu;%zu\n", "ArvGcStringRegNode", sizeof(ArvGcStringRegNode), alignof(ArvGcStringRegNode));
printf("%s;%zu;%zu\n", "ArvGcStringRegNodeClass", sizeof(ArvGcStringRegNodeClass), alignof(ArvGcStringRegNodeClass));
printf("%s;%zu;%zu\n", "ArvGcStructEntryNodeClass", sizeof(ArvGcStructEntryNodeClass), alignof(ArvGcStructEntryNodeClass));
printf("%s;%zu;%zu\n", "ArvGcStructRegNode", sizeof(ArvGcStructRegNode), alignof(ArvGcStructRegNode));
printf("%s;%zu;%zu\n", "ArvGcStructRegNodeClass", sizeof(ArvGcStructRegNodeClass), alignof(ArvGcStructRegNodeClass));
printf("%s;%zu;%zu\n", "ArvGcSwissKnife", sizeof(ArvGcSwissKnife), alignof(ArvGcSwissKnife));
printf("%s;%zu;%zu\n", "ArvGcSwissKnifeClass", sizeof(ArvGcSwissKnifeClass), alignof(ArvGcSwissKnifeClass));
printf("%s;%zu;%zu\n", "ArvGcSwissKnifeNode", sizeof(ArvGcSwissKnifeNode), alignof(ArvGcSwissKnifeNode));
printf("%s;%zu;%zu\n", "ArvGcSwissKnifeNodeClass", sizeof(ArvGcSwissKnifeNodeClass), alignof(ArvGcSwissKnifeNodeClass));
printf("%s;%zu;%zu\n", "ArvGcValueIndexedNodeClass", sizeof(ArvGcValueIndexedNodeClass), alignof(ArvGcValueIndexedNodeClass));
printf("%s;%zu;%zu\n", "ArvGcVisibility", sizeof(ArvGcVisibility), alignof(ArvGcVisibility));
printf("%s;%zu;%zu\n", "ArvGvDeviceClass", sizeof(ArvGvDeviceClass), alignof(ArvGvDeviceClass));
printf("%s;%zu;%zu\n", "ArvGvFakeCameraClass", sizeof(ArvGvFakeCameraClass), alignof(ArvGvFakeCameraClass));
printf("%s;%zu;%zu\n", "ArvGvInterfaceClass", sizeof(ArvGvInterfaceClass), alignof(ArvGvInterfaceClass));
printf("%s;%zu;%zu\n", "ArvGvPacketSizeAdjustment", sizeof(ArvGvPacketSizeAdjustment), alignof(ArvGvPacketSizeAdjustment));
printf("%s;%zu;%zu\n", "ArvGvStreamClass", sizeof(ArvGvStreamClass), alignof(ArvGvStreamClass));
printf("%s;%zu;%zu\n", "ArvGvStreamOption", sizeof(ArvGvStreamOption), alignof(ArvGvStreamOption));
printf("%s;%zu;%zu\n", "ArvGvStreamPacketResend", sizeof(ArvGvStreamPacketResend), alignof(ArvGvStreamPacketResend));
printf("%s;%zu;%zu\n", "ArvGvStreamSocketBuffer", sizeof(ArvGvStreamSocketBuffer), alignof(ArvGvStreamSocketBuffer));
printf("%s;%zu;%zu\n", "ArvInterface", sizeof(ArvInterface), alignof(ArvInterface));
printf("%s;%zu;%zu\n", "ArvInterfaceClass", sizeof(ArvInterfaceClass), alignof(ArvInterfaceClass));
printf("%s;%zu;%zu\n", "ArvPixelFormat", sizeof(ArvPixelFormat), alignof(ArvPixelFormat));
printf("%s;%zu;%zu\n", "ArvRangeCheckPolicy", sizeof(ArvRangeCheckPolicy), alignof(ArvRangeCheckPolicy));
printf("%s;%zu;%zu\n", "ArvRegisterCachePolicy", sizeof(ArvRegisterCachePolicy), alignof(ArvRegisterCachePolicy));
printf("%s;%zu;%zu\n", "ArvStream", sizeof(ArvStream), alignof(ArvStream));
printf("%s;%zu;%zu\n", "ArvStreamCallbackType", sizeof(ArvStreamCallbackType), alignof(ArvStreamCallbackType));
printf("%s;%zu;%zu\n", "ArvStreamClass", sizeof(ArvStreamClass), alignof(ArvStreamClass));
printf("%s;%zu;%zu\n", "ArvUvDeviceClass", sizeof(ArvUvDeviceClass), alignof(ArvUvDeviceClass));
printf("%s;%zu;%zu\n", "ArvUvInterfaceClass", sizeof(ArvUvInterfaceClass), alignof(ArvUvInterfaceClass));
printf("%s;%zu;%zu\n", "ArvUvStreamClass", sizeof(ArvUvStreamClass), alignof(ArvUvStreamClass));
printf("%s;%zu;%zu\n", "ArvXmlSchemaClass", sizeof(ArvXmlSchemaClass), alignof(ArvXmlSchemaClass));
printf("%s;%zu;%zu\n", "ArvXmlSchemaError", sizeof(ArvXmlSchemaError), alignof(ArvXmlSchemaError));
return 0;
}
|
ryancwicks/aravis-rs
|
aravis-sys/tests/constant.c
|
// Generated by gir (https://github.com/gtk-rs/gir @ e8f82cf)
// from ../gir-files (@ 6f12897)
// DO NOT EDIT
#include "manual.h"
#include <stdio.h>
#define PRINT_CONSTANT(CONSTANT_NAME) \
printf("%s;", #CONSTANT_NAME); \
printf(_Generic((CONSTANT_NAME), \
char *: "%s", \
const char *: "%s", \
char: "%c", \
signed char: "%hhd", \
unsigned char: "%hhu", \
short int: "%hd", \
unsigned short int: "%hu", \
int: "%d", \
unsigned int: "%u", \
long: "%ld", \
unsigned long: "%lu", \
long long: "%lld", \
unsigned long long: "%llu", \
float: "%f", \
double: "%f", \
long double: "%ld"), \
CONSTANT_NAME); \
printf("\n");
int main() {
PRINT_CONSTANT((gint) ARV_ACQUISITION_MODE_CONTINUOUS);
PRINT_CONSTANT((gint) ARV_ACQUISITION_MODE_MULTI_FRAME);
PRINT_CONSTANT((gint) ARV_ACQUISITION_MODE_SINGLE_FRAME);
PRINT_CONSTANT((gint) ARV_AUTO_CONTINUOUS);
PRINT_CONSTANT((gint) ARV_AUTO_OFF);
PRINT_CONSTANT((gint) ARV_AUTO_ONCE);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_CHUNK_DATA);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_EXTENDED_CHUNK_DATA);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_FILE);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_H264);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_IMAGE);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_IMAGE_EXTENDED_CHUNK);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_JPEG);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_JPEG2000);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_MULTIZONE_IMAGE);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_RAWDATA);
PRINT_CONSTANT((gint) ARV_BUFFER_PAYLOAD_TYPE_UNKNOWN);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_ABORTED);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_CLEARED);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_FILLING);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_MISSING_PACKETS);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_SIZE_MISMATCH);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_SUCCESS);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_TIMEOUT);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_UNKNOWN);
PRINT_CONSTANT((gint) ARV_BUFFER_STATUS_WRONG_PACKET_ID);
PRINT_CONSTANT((gint) ARV_CHUNK_PARSER_ERROR_BUFFER_NOT_FOUND);
PRINT_CONSTANT((gint) ARV_CHUNK_PARSER_ERROR_CHUNK_NOT_FOUND);
PRINT_CONSTANT((gint) ARV_CHUNK_PARSER_ERROR_INVALID_FEATURE_TYPE);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_FEATURE_NOT_FOUND);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_GENICAM_NOT_FOUND);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_INVALID_PARAMETER);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_NOT_CONNECTED);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_NOT_CONTROLLER);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_NOT_FOUND);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_NO_STREAM_CHANNEL);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_PROTOCOL_ERROR);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_TIMEOUT);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_TRANSFER_ERROR);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_UNKNOWN);
PRINT_CONSTANT((gint) ARV_DEVICE_ERROR_WRONG_FEATURE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_ATTRIBUTE_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_CDATA_SECTION_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_COMMENT_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_DOCUMENT_FRAGMENT_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_DOCUMENT_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_DOCUMENT_TYPE_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_ELEMENT_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_ENTITY_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_ENTITY_REFERENCE_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_NOTATION_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_PROCESSING_INSTRUCTION_NODE);
PRINT_CONSTANT((gint) ARV_DOM_NODE_TYPE_TEXT_NODE);
PRINT_CONSTANT((gint) ARV_EXPOSURE_MODE_OFF);
PRINT_CONSTANT((gint) ARV_EXPOSURE_MODE_TIMED);
PRINT_CONSTANT((gint) ARV_EXPOSURE_MODE_TRIGGER_CONTROLLED);
PRINT_CONSTANT((gint) ARV_EXPOSURE_MODE_TRIGGER_WIDTH);
PRINT_CONSTANT(ARV_FAKE_CAMERA_ACQUISITION_FRAME_RATE_DEFAULT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_BINNING_HORIZONTAL_DEFAULT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_BINNING_VERTICAL_DEFAULT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_EXPOSURE_TIME_US_DEFAULT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_HEIGHT_DEFAULT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_MEMORY_SIZE);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_ACQUISITION);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_ACQUISITION_FRAME_PERIOD_US);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_ACQUISITION_MODE);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_ACQUISITION_START_OFFSET);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_BINNING_HORIZONTAL);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_BINNING_VERTICAL);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_EXPOSURE_TIME_US);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_FRAME_START_OFFSET);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_GAIN_MODE);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_GAIN_RAW);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_HEIGHT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_PIXEL_FORMAT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_SENSOR_HEIGHT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_SENSOR_WIDTH);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_TEST);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_TRIGGER_ACTIVATION);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_TRIGGER_MODE);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_TRIGGER_SOURCE);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_WIDTH);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_X_OFFSET);
PRINT_CONSTANT(ARV_FAKE_CAMERA_REGISTER_Y_OFFSET);
PRINT_CONSTANT(ARV_FAKE_CAMERA_SENSOR_HEIGHT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_SENSOR_WIDTH);
PRINT_CONSTANT(ARV_FAKE_CAMERA_TEST_REGISTER_DEFAULT);
PRINT_CONSTANT(ARV_FAKE_CAMERA_WIDTH_DEFAULT);
PRINT_CONSTANT((gint) ARV_GC_ACCESS_MODE_RO);
PRINT_CONSTANT((gint) ARV_GC_ACCESS_MODE_RW);
PRINT_CONSTANT((gint) ARV_GC_ACCESS_MODE_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_ACCESS_MODE_WO);
PRINT_CONSTANT((gint) ARV_GC_CACHABLE_NO_CACHE);
PRINT_CONSTANT((gint) ARV_GC_CACHABLE_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_CACHABLE_WRITE_AROUND);
PRINT_CONSTANT((gint) ARV_GC_CACHABLE_WRITE_THROUGH);
PRINT_CONSTANT((gint) ARV_GC_DISPLAY_NOTATION_AUTOMATIC);
PRINT_CONSTANT((gint) ARV_GC_DISPLAY_NOTATION_FIXED);
PRINT_CONSTANT((gint) ARV_GC_DISPLAY_NOTATION_SCIENTIFIC);
PRINT_CONSTANT((gint) ARV_GC_DISPLAY_NOTATION_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_ERROR_EMPTY_ENUMERATION);
PRINT_CONSTANT((gint) ARV_GC_ERROR_ENUM_ENTRY_NOT_FOUND);
PRINT_CONSTANT((gint) ARV_GC_ERROR_GET_AS_STRING_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_ERROR_INVALID_BIT_RANGE);
PRINT_CONSTANT((gint) ARV_GC_ERROR_INVALID_LENGTH);
PRINT_CONSTANT((gint) ARV_GC_ERROR_INVALID_PVALUE);
PRINT_CONSTANT((gint) ARV_GC_ERROR_NODE_NOT_FOUND);
PRINT_CONSTANT((gint) ARV_GC_ERROR_NO_DEVICE_SET);
PRINT_CONSTANT((gint) ARV_GC_ERROR_NO_EVENT_IMPLEMENTATION);
PRINT_CONSTANT((gint) ARV_GC_ERROR_OUT_OF_RANGE);
PRINT_CONSTANT((gint) ARV_GC_ERROR_PROPERTY_NOT_DEFINED);
PRINT_CONSTANT((gint) ARV_GC_ERROR_PVALUE_NOT_DEFINED);
PRINT_CONSTANT((gint) ARV_GC_ERROR_READ_ONLY);
PRINT_CONSTANT((gint) ARV_GC_ERROR_SET_FROM_STRING_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_IS_LINEAR_NO);
PRINT_CONSTANT((gint) ARV_GC_IS_LINEAR_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_IS_LINEAR_YES);
PRINT_CONSTANT((gint) ARV_GC_NAME_SPACE_CUSTOM);
PRINT_CONSTANT((gint) ARV_GC_NAME_SPACE_STANDARD);
PRINT_CONSTANT((gint) ARV_GC_NAME_SPACE_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_ACCESS_MODE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_ADDRESS);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_BIT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_CACHABLE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_CHUNK_ID);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_COMMAND_VALUE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_CONSTANT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_DESCRIPTION);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_DISPLAY_NAME);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_DISPLAY_NOTATION);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_DISPLAY_PRECISION);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_ENDIANNESS);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_EVENT_ID);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_EXPRESSION);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_FORMULA);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_FORMULA_FROM);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_FORMULA_TO);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_IMPOSED_ACCESS_MODE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_INCREMENT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_IS_LINEAR);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_LENGTH);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_LSB);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_MAXIMUM);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_MINIMUM);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_MSB);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_OFF_VALUE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_ON_VALUE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_POLLING_TIME);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_ADDRESS);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_COMMAND_VALUE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_FEATURE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_INCREMENT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_INDEX);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_INVALIDATOR);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_IS_AVAILABLE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_IS_IMPLEMENTED);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_IS_LOCKED);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_LENGTH);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_MAXIMUM);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_MINIMUM);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_PORT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_SELECTED);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_UNKNONW);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_VALUE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_VALUE_DEFAULT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_VALUE_INDEXED);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_P_VARIABLE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_REPRESENTATION);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_SIGN);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_SLOPE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_STREAMABLE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_TOOLTIP);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_UNIT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_UNKNOWN);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_VALUE);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_VALUE_DEFAULT);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_VALUE_INDEXED);
PRINT_CONSTANT((gint) ARV_GC_PROPERTY_NODE_TYPE_VISIBILITY);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_BOOLEAN);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_HEX_NUMBER);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_IPV4_ADDRESS);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_LINEAR);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_LOGARITHMIC);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_MAC_ADDRESS);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_PURE_NUMBER);
PRINT_CONSTANT((gint) ARV_GC_REPRESENTATION_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_SIGNEDNESS_SIGNED);
PRINT_CONSTANT((gint) ARV_GC_SIGNEDNESS_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_SIGNEDNESS_UNSIGNED);
PRINT_CONSTANT((gint) ARV_GC_STREAMABLE_NO);
PRINT_CONSTANT((gint) ARV_GC_STREAMABLE_UNDEFINED);
PRINT_CONSTANT((gint) ARV_GC_STREAMABLE_YES);
PRINT_CONSTANT((gint) ARV_GC_VISIBILITY_BEGINNER);
PRINT_CONSTANT((gint) ARV_GC_VISIBILITY_EXPERT);
PRINT_CONSTANT((gint) ARV_GC_VISIBILITY_GURU);
PRINT_CONSTANT((gint) ARV_GC_VISIBILITY_INVISIBLE);
PRINT_CONSTANT((gint) ARV_GC_VISIBILITY_UNDEFINED);
PRINT_CONSTANT(ARV_GV_FAKE_CAMERA_DEFAULT_INTERFACE);
PRINT_CONSTANT(ARV_GV_FAKE_CAMERA_DEFAULT_SERIAL_NUMBER);
PRINT_CONSTANT((gint) ARV_GV_PACKET_SIZE_ADJUSTMENT_ALWAYS);
PRINT_CONSTANT((gint) ARV_GV_PACKET_SIZE_ADJUSTMENT_DEFAULT);
PRINT_CONSTANT((gint) ARV_GV_PACKET_SIZE_ADJUSTMENT_NEVER);
PRINT_CONSTANT((gint) ARV_GV_PACKET_SIZE_ADJUSTMENT_ONCE);
PRINT_CONSTANT((gint) ARV_GV_PACKET_SIZE_ADJUSTMENT_ON_FAILURE);
PRINT_CONSTANT((gint) ARV_GV_PACKET_SIZE_ADJUSTMENT_ON_FAILURE_ONCE);
PRINT_CONSTANT((gint) ARV_GV_STREAM_OPTION_NONE);
PRINT_CONSTANT((gint) ARV_GV_STREAM_OPTION_PACKET_SOCKET_DISABLED);
PRINT_CONSTANT((gint) ARV_GV_STREAM_PACKET_RESEND_ALWAYS);
PRINT_CONSTANT((gint) ARV_GV_STREAM_PACKET_RESEND_NEVER);
PRINT_CONSTANT((gint) ARV_GV_STREAM_SOCKET_BUFFER_AUTO);
PRINT_CONSTANT((gint) ARV_GV_STREAM_SOCKET_BUFFER_FIXED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_10);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_10P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_10_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_12);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_12P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_BG_8);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_10);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_10P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_10_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_12);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_12P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GB_8);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_10);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_10P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_10_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_12);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_12P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_GR_8);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_10);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_10P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_10_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_12);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_12P);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BAYER_RG_8);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BGRA_8_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BGR_10_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BGR_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_BGR_8_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_BG_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_BG_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_GB_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_GB_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_GR_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_GR_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_RG_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_BAYER_RG_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_CUSTOM_YUV_422_YUYV_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_10);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_10_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_12);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_14);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_16);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_8);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_MONO_8_SIGNED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGBA_8_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGB_10_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGB_10_PLANAR);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGB_12_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGB_12_PLANAR);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGB_16_PLANAR);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGB_8_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_RGB_8_PLANAR);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_YUV_411_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_YUV_422_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_YUV_422_YUYV_PACKED);
PRINT_CONSTANT(ARV_PIXEL_FORMAT_YUV_444_PACKED);
PRINT_CONSTANT((gint) ARV_RANGE_CHECK_POLICY_DEBUG);
PRINT_CONSTANT((gint) ARV_RANGE_CHECK_POLICY_DEFAULT);
PRINT_CONSTANT((gint) ARV_RANGE_CHECK_POLICY_DISABLE);
PRINT_CONSTANT((gint) ARV_RANGE_CHECK_POLICY_ENABLE);
PRINT_CONSTANT((gint) ARV_REGISTER_CACHE_POLICY_DEBUG);
PRINT_CONSTANT((gint) ARV_REGISTER_CACHE_POLICY_DEFAULT);
PRINT_CONSTANT((gint) ARV_REGISTER_CACHE_POLICY_DISABLE);
PRINT_CONSTANT((gint) ARV_REGISTER_CACHE_POLICY_ENABLE);
PRINT_CONSTANT((gint) ARV_STREAM_CALLBACK_TYPE_BUFFER_DONE);
PRINT_CONSTANT((gint) ARV_STREAM_CALLBACK_TYPE_EXIT);
PRINT_CONSTANT((gint) ARV_STREAM_CALLBACK_TYPE_INIT);
PRINT_CONSTANT((gint) ARV_STREAM_CALLBACK_TYPE_START_BUFFER);
PRINT_CONSTANT((gint) ARV_XML_SCHEMA_ERROR_INVALID_STRUCTURE);
return 0;
}
|
Mandrilux/game_pendu
|
check.c
|
/*
** check.c for in /home/baptiste/rendu/game_pendu
**
** Made by
** Login <<EMAIL>>
**
** Started on Sun May 29 18:01:54 2016
** Last update Thu Jun 2 20:45:18 2016
*/
#include "my.h"
int count_tab(char **tab)
{
int i = -1;
if (tab == NULL)
return (0);
while (tab[++i] != NULL);
return (i);
}
int is_end(char *str)
{
int i = -1;
while (str[++i] != '\0')
{
if (str[i] == '_')
return (0);
}
return (1);
}
int check_word(char *mystere, char *search, char c)
{
int i = -1;
int flag = 0;
while (mystere[++i] != '\0')
{
if (mystere[i] == c)
{
search[i] = c;
flag++;
}
}
return (flag);
}
|
Mandrilux/game_pendu
|
init.c
|
<filename>init.c
/*
** init.c for in /home/baptiste/rendu/game_pendu
**
** Made by
** Login <<EMAIL>>
**
** Started on Sun May 29 17:50:12 2016
** Last update Sun May 29 18:56:55 2016
*/
#include "my.h"
char *init_word()
{
int fd;
char **tab_word = NULL;
char *line;
if ((fd = open("word.txt", O_RDONLY)) == -1)
{
printf("Erreur d'ouverture du fichier\n");
exit(EXIT_FAILURE);
}
while ((line = get_next_line(fd)) != NULL)
{
if ((tab_word = alloc(tab_word, line)) == NULL)
return (NULL);
}
close(fd);
srand(time(NULL));
return (tab_word[(rand() % (count_tab(tab_word) - 1))]);
}
char *word_search(char *word)
{
char *search;
if ((search = malloc(sizeof(char) * (strlen(word) + 1))) == NULL)
return (NULL);
memset(search, '\0', strlen(word) + 1);
memset(search, '_', strlen(word));
return (search);
}
|
Mandrilux/game_pendu
|
main.c
|
/*
** main.c for in /home/baptiste/rendu/game_pendu
**
** Made by
** Login <<EMAIL>>
**
** Started on Sun May 29 17:48:59 2016
** Last update Thu Jun 2 20:57:07 2016
*/
#include "my.h"
int main()
{
char *word;
char *search;
char *c;
int end;
end = 10;
if ((word = init_word()) == NULL)
{
printf("Erreur lors de l'initialisation du programme");
return (EXIT_FAILURE);
}
if ((search = word_search(word)) == NULL)
{
printf("Erreur lors de l'initialisation du programme");
return (EXIT_FAILURE);
}
while (is_end(search) == 0 && end != 0)
{
printf("Le mot découvert est : %s\n", search);
if ((c = get_next_line(0)) == NULL)
return (EXIT_FAILURE);
if (c[0] != '\0' && c[0] != '\n' && strlen(c) == 1)
{
if (check_word(word, search, c[0]) == 0)
end--;
}
display_scoring(end);
free(c);
}
return (display_end(end, word));
}
int display_end(int end, char *word)
{
if (end == 0)
printf("Vous avez perdu ! ");
else
{
printf("Bravo vous avez gagné ! ");
save_score(end, word);
}
printf("Le mot mystere etais %s.\n",word);
return (EXIT_SUCCESS);
}
void display_scoring(int end)
{
if (end != 0)
{
if (end == 1)
printf("il vous reste 1 essai\n");
else
printf("Il vous reste %d essais\n", end);
}
}
|
Mandrilux/game_pendu
|
include/my.h
|
<reponame>Mandrilux/game_pendu<gh_stars>0
/*
** my.h for in /home/baptiste/project/clean_project
**
** Made by
** Login <<EMAIL>>
**
** Started on Wed May 18 12:49:26 2016
** Last update Sun May 29 18:42:32 2016
*/
#ifndef MY_H_
#define MY_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include "get_next_line.h"
/* check.c */
int count_tab(char **tab);
int is_end(char *str);
int check_word(char *mystere, char *search, char c);
/* init.c */
char *init_word();
char *word_search(char *word);
/* str.c */
char **alloc(char **re_write, char *name);
int save_score(int tour, char *str);
/* get_line.c */
int my_memset_len(char *s, char c, int size, int flag);
/* main.c */
int main();
int display_end(int end, char *word);
void display_scoring(int end);
#endif /* MY_H_ */
|
Mandrilux/game_pendu
|
str.c
|
<reponame>Mandrilux/game_pendu
/*
** str.c for in /home/baptiste/rendu/game_pendu
**
** Made by
** Login <<EMAIL>>
**
** Started on Sun May 29 18:00:57 2016
** Last update Thu Jun 2 21:00:25 2016
*/
#include "my.h"
char **alloc(char **re_write, char *name)
{
int i;
char **tmp;
i = -1;
if (re_write == NULL)
{
if ((tmp = malloc(sizeof(char *) * 2)) == NULL)
return (NULL);
tmp[0] = name;
tmp[1] = NULL;
}
else
{
if ((tmp = malloc(sizeof(char *) *
(count_tab(re_write) + 2))) == NULL)
return (NULL);
while (re_write[++i] != NULL)
tmp[i] = re_write[i];
tmp[i] = name;
tmp[i + 1] = NULL;
}
return (tmp);
}
int save_score(int tour, char *str)
{
FILE* score = NULL;
char *name;
printf("\nEntrez un nom ! \n");
if ((name = get_next_line(0)) == NULL)
return (-1);
score = fopen("score.txt", "w");
if (score != NULL)
{
fprintf(score, "[%s] trouvé en %d tour par %s", str, tour, name);
fclose(score);
}
return (1);
}
|
jonahisadev/nitrogen
|
include/Nitrogen/Context.h
|
#ifndef NITROGEN_CONTEXT_H
#define NITROGEN_CONTEXT_H
#include <cstdlib>
#include <cstring>
#include <Nitrogen/Util.h>
#include <Nitrogen/List.h>
#include <Nitrogen/Token.h>
#include <Nitrogen/Compiler.h>
#include <Nitrogen/Type.h>
namespace Nitrogen {
class Context {
private:
LinkedList<Token*>* tokens;
List<char*>* names;
List<char*>* ids;
List<Type*>* types;
List<Expression*>* exprs;
public:
Context();
~Context();
void start();
void createExpression(LinkData<Token*>* start);
Compiler* createCompiler();
void setTokens(LinkedList<Token*>* tokens) { this->tokens = tokens; };
void setNames(List<char*>* names) { this->names = names; };
void setTypes(List<Type*>* types) { this->types = types; }
};
}
#endif // NITROGEN_CONTEXT_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Type.h
|
<filename>include/Nitrogen/Type.h
#ifndef NITROGEN_TYPE_H
#define NITROGEN_TYPE_H
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <Nitrogen/List.h>
namespace Nitrogen {
struct Type {
const char* name;
int size;
bool primitive;
Type(const char* name, int size, bool primitive) {
this->name = strdup(name);
this->size = size;
this->primitive = primitive;
}
~Type() {
delete this->name;
}
};
struct Variable {
const char* name;
Type* type;
bool array;
// int data;
Variable(const char* name, Type* type) {
this->name = strdup(name);
this->type = type;
// this->data = data;
}
~Variable() {
delete this->name;
}
};
template class List<Variable*>;
enum FunctionType {
F_LOCAL,
F_NATIVE,
};
struct Function {
const char* name;
Type* ret;
List<Variable*>* params;
List<Variable*>* locals;
int type = F_LOCAL;
Function(const char* name) {
this->name = strdup(name);
this->params = new List<Variable*>(1);
this->locals = new List<Variable*>(1);
}
~Function() {
delete this->name;
}
int isParam(const char* str) {
for (int i = 0; i < params->getSize(); i++) {
if (!strcmp(params->get(i)->name, str)) {
return i;
}
}
return -1;
}
int getParamOffset(int index) {
int size = 0;
for (int i = 0; i < index; i++) {
size += params->get(i)->type->size;
}
return size;
}
void setReturnType(Type* ret) { this->ret = ret; }
void addParam(Variable* param) { this->params->add(param); }
void addLocal(Variable* local) { this->locals->add(local); }
void setType(int type) { this->type = type; };
};
}
#endif // NITROGEN_TYPE_H
|
jonahisadev/nitrogen
|
include/Nitrogen/LinkedList.h
|
#ifndef NITROGEN_LINKEDLIST_H
#define NITROGEN_LINKEDLIST_H
#include <cstdio>
namespace Nitrogen {
template <class T>
struct LinkData {
LinkData<T>* parent;
LinkData<T>* child;
T data;
LinkData(LinkData<T>* parent, LinkData<T>* child, T data) {
this->parent = parent;
this->child = child;
this->data = data;
}
bool hasChild() {
if (child) {
return true;
}
return false;
}
void insertBefore(LinkData<T>* data) {
LinkData<T>* psave = this->parent;
// Set link between current and new
this->parent = data;
data->child = this;
// Set link between old parent and new
data->parent = psave;
psave->child = data;
}
void insertAfter(LinkData<T>* data) {
LinkData<T>* csave = this->child;
// Set link between current and new
this->child = data;
data->parent = this;
// Set link between old child and new
data->child = csave;
csave->parent = data;
}
void remove() {
child->parent = parent;
parent->child = child;
this->parent = nullptr;
this->child = nullptr;
}
};
template <class T>
class LinkedList {
private:
LinkData<T>* root;
LinkData<T>* tail;
LinkData<T>* current;
public:
LinkedList(T root);
~LinkedList();
void add(T data);
LinkData<T>* get(int index);
T getData(int index);
LinkData<T>* getRelative(int offset);
LinkData<T>* child(LinkData<T>* current);
LinkData<T>* parent(LinkData<T>* current);
void setCurrent(LinkData<T>* current);
LinkData<T>* getCurrent() const { return current; }
};
template class LinkedList<int>;
template <class T>
LinkedList<T>::LinkedList(T root) {
this->root = new LinkData<T>(nullptr, nullptr, root);
this->tail = this->root;
}
template <class T>
LinkedList<T>::~LinkedList() {
LinkData<T>* current = this->root;
int count = 0;
while (current->child != nullptr) {
current = child(current);
count++;
}
LinkData<T>* temp;
for (int i = 0; i < count; i++) {
temp = current->parent;
delete current;
current = temp;
}
}
template <class T>
void LinkedList<T>::add(T data) {
// LinkData<T>* tailSave = this->tail;
this->tail->child = new LinkData<T>(this->tail, nullptr, data);
this->tail = this->tail->child;
// this->tail->parent = tailSave;
}
template <class T>
LinkData<T>* LinkedList<T>::get(int index) {
LinkData<T>* current = this->root->child;
for (int i = 0; i < index; i++) {
current = current->child;
}
this->current = current;
return current;
}
template <class T>
T LinkedList<T>::getData(int index) {
LinkData<T>* ld = get(index);
return ld->data;
}
template <class T>
LinkData<T>* LinkedList<T>::getRelative(int offset) {
LinkData<T>* current = this->current;
if (offset < 0) {
offset = -offset;
for (int i = 0; i < offset; i++) {
current = current->parent;
}
} else if (offset > 0) {
for (int i = 0; i < offset; i++) {
current = current->child;
}
}
return current;
}
template <class T>
LinkData<T>* LinkedList<T>::child(LinkData<T>* current) {
LinkData<T>* child = current->child;
this->current = child;
return child;
}
template <class T>
LinkData<T>* LinkedList<T>::parent(LinkData<T>* current) {
LinkData<T>* parent = current->parent;
this->current = parent;
return parent;
}
template <class T>
void LinkedList<T>::setCurrent(LinkData<T>* current) {
this->current = current;
}
}
#endif // NITROGEN_LINKEDLIST_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Expression.h
|
#ifndef NITROGEN_EXPRESSION_H
#define NITROGEN_EXPRESSION_H
#include <Nitrogen/Token.h>
#include <Nitrogen/Util.h>
#include <Nitrogen/List.h>
#include <Nitrogen/Type.h>
#include <Nitrogen/Compiler.h>
#include <cstdio>
namespace Nitrogen {
struct ExprNode {
ExprNode* parent = nullptr;
ExprNode* left = nullptr;
ExprNode* right = nullptr;
int type;
int data;
ExprNode(int type, int data) {
this->type = type;
this->data = data;
}
void addChild(ExprNode* en) {
if (left == nullptr) {
this->left = en;
} else {
this->right = en;
}
}
int childCount() {
if (!left)
return 0;
else if (!right)
return 1;
else
return 2;
}
};
class Compiler;
class Expression {
private:
ExprNode* root;
ExprNode* current;
public:
Expression();
~Expression();
void addOp(int data);
void addNumber(int data);
void addVariable(int data);
List<char*>* evaluate(FILE* out, Compiler* compiler);
const char* getOpName(int data);
ExprNode* getNumber(ExprNode* a, ExprNode* b);
ExprNode* getVariable(ExprNode* a, ExprNode* b);
ExprNode* getRoot() const { return root; }
};
}
#endif // NITROGEN_EXPRESSION_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Parser.h
|
<gh_stars>1-10
#ifndef NITROGEN_PARSER_H
#define NITROGEN_PARSER_H
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <Nitrogen/List.h>
#include <Nitrogen/Token.h>
#include <Nitrogen/Util.h>
#include <Nitrogen/Context.h>
#include <Nitrogen/LinkedList.h>
namespace Nitrogen {
class Parser {
private:
char* source;
int length;
// List<Token*>* tokens;
LinkedList<Token*>* tokens;
List<char*>* names;
List<Type*>* types;
bool comment = false;
public:
Parser(char* source, int length);
~Parser();
void start();
bool isImportant(char c);
int isKeyword(char* str);
int isType(char* str);
Context* createContext();
// int getListSize() const { return tokens->getSize(); }
};
}
#endif // NITROGEN_PARSER_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Util.h
|
<reponame>jonahisadev/nitrogen<filename>include/Nitrogen/Util.h
#ifndef NITROGEN_UTIL_H
#define NITROGEN_UTIL_H
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define TEMP_BUF_SIZE 256
#define error(...) fprintf(stderr, "\033[1;31m"); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\033[0m"); exit(1);
namespace Nitrogen {
class Util {
public:
// Files
static char* readFile(const char* path, int* length);
// Numbers
static bool isNumber(const char* str);
static int toNum(const char* str, int base);
// Buffers
static char* createTempBuffer();
static void clearTempBuffer(char* buf);
};
}
#endif // NITROGEN_UTIL_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Template.h
|
#ifndef NITROGEN_TEMPLATE_H
#define NITROGEN_TEMPLATE_H
namespace Nitrogen {
static const char* VM_START =
R"str(; Auto generated by Nitrogen Compiler
; Do NOT edit!
#include "tests/lib/nitrogen.nvm"
#section TEXT
)str";
static const char* VM_START_END =
R"str( call @_main
mov ebx erx
exit
)str";
static const char* VM_RETURN_CONST =
R"str( mov erx %d
)str";
static const char* VM_RETURN_G_VAR =
R"str( ld%s erx $g_%s
)str";
static const char* VM_RETURN_P_VAR =
R"str( %sget erx (ebp)+%d
)str";
static const char* VM_VAR_DEC_AND_INIT =
R"str(g_%s: d%s %d
)str";
static const char* VM_VAR_SET =
R"str( st%s $g_%s %d
)str";
static const char* VM_VAR_SET_E =
R"str( st%s $g_%s %s
)str";
static const char* VM_CALL_HEADER =
R"str( pusha
)str";
static const char* VM_CALL_END =
R"str( call @_%s
add esp %d
popa
)str";
static const char* VM_CALL_NATIVE =
R"str( ncall %%%s
add esp %d
popa
)str";
}
#endif // NITROGEN_TEMPLATE_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Compiler.h
|
#ifndef NITROGEN_COMPILER_H
#define NITROGEN_COMPILER_H
#include <cstdio>
#include <cstdlib>
#include <Nitrogen/Util.h>
#include <Nitrogen/Token.h>
#include <Nitrogen/List.h>
#include <Nitrogen/Template.h>
#include <Nitrogen/Type.h>
#include <Nitrogen/Struct.h>
#include <Nitrogen/Expression.h>
namespace Nitrogen {
class Expression;
class Compiler {
private:
FILE* out;
LinkedList<Token*>* tokens;
List<char*>* names;
List<char*>* ids;
List<Type*>* types;
List<Variable*>* gvars;
List<Function*>* funcs;
List<Expression*>* exprs;
List<Struct*>* structs;
List<char*>* varBuffer;
List<char*>* initBuffer;
Function* currentFunction = nullptr;
public:
Compiler();
~Compiler();
void start();
void getNatives();
int insideFunction(LinkData<Token*>* current, Token* t, Function* currentFunction);
Function* createFunction(LinkData<Token*>* func);
void parseFunctionCall(LinkData<Token*>* func);
Struct* createStruct(LinkData<Token*>* s, int* offset);
void createStructConstructor(Struct* s, Function* f);
void setTokens(LinkedList<Token*>* tokens) { this->tokens = tokens; };
void setNames(List<char*>* names) { this->names = names; };
void setIDs(List<char*>* ids) { this->ids = ids; };
void setTypes(List<Type*>* types) { this->types = types; }
void setExpressions(List<Expression*>* exprs) { this->exprs = exprs; }
const char* getStoreSize(Variable* var);
const char* getInstSize(Variable* v);
Struct* getStructByName(const char* name);
// For expression parser
Variable* getGlobalVariable(int index) { return this->gvars->get(index); }
Function* getCurrentFunction() { return this->currentFunction; }
char* getName(int index) { return this->names->get(index); }
int isFunction(char* name);
int isGlobal(char* name);
};
}
#endif // NITROGEN_COMPILER_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Token.h
|
<reponame>jonahisadev/nitrogen
#ifndef NITROGEN_TOKEN_H
#define NITROGEN_TOKEN_H
#include <Nitrogen/List.h>
#include <Nitrogen/LinkedList.h>
namespace Nitrogen {
enum TokenType {
KEYWORD,
NUMBER,
SPECIAL,
OP,
EXPR,
NAME,
ID,
TYPE,
VAR, // Generic
GVAR, // Global
PVAR, // Parameter
LVAR, // Local
};
enum TokenKeyword {
FUNC,
RETURN,
ENDF,
NATIVE,
STRUCT,
END,
DOLLAR,
};
enum TokenSpecial {
LEFT_PAR,
RIGHT_PAR,
LEFT_BRACK,
RIGHT_BRACK,
COLON,
COMMA,
EXCLAIM,
DOT,
HASH,
STAR,
};
enum TokenOperators {
EQUALS,
PLUS,
MINUS,
};
class Token;
template class List<Token*>;
template class LinkedList<Token*>;
class Token {
private:
int type;
int data;
int line;
public:
Token(int type, int data, int line);
~Token();
int getType() const { return type; }
int getData() const { return data; }
int getLine() const { return line; }
void setType(int type) { this->type = type; }
void setData(int data) { this->data = data; }
};
}
#endif // NITROGEN_TOKEN_H
|
jonahisadev/nitrogen
|
include/Nitrogen/Struct.h
|
<reponame>jonahisadev/nitrogen
#ifndef NITROGEN_STRUCT_H
#define NITROGEN_STRUCT_H
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <Nitrogen/Util.h>
#include <Nitrogen/List.h>
#include <Nitrogen/Type.h>
namespace Nitrogen {
class Struct {
public:
char* name;
List<Variable*>* vars;
List<Function*>* funcs;
int size;
Struct(char* name);
~Struct();
void addVariable(Variable* v);
Variable* getVariable(char* str);
Function* getFunction(const char* str);
};
template class List<Struct*>;
}
#endif // NITROGEN_STRUCT_H
|
iLambda/ym2612-glue
|
src/ym2612.c
|
#include "ym2612.h"
uint8_t ym2612_init(uint8_t* cb, uint8_t* cd, uint8_t* db, uint8_t* dd) {
// Save buses
controlbus = (ymcontrolbus_t*)(void*)cb;
controldir = cd;
databus = db;
datadir = dd;
// Direction setup
*controldir = 0x00;
*datadir = 0x00;
// Bus setup
controlbus->ic = 1;
controlbus->cs = 1;
controlbus->wr = 1;
controlbus->rd = 1;
controlbus->a0 = 0;
controlbus->a1 = 0;
// Activate PWM for YM2612 clock
PWM1_Init(8000);
PWM1_Set_Duty(0x7F);
PWM1_Start();
// Reset
controlbus->ic = 0;
delay_ms(10);
controlbus->ic = 1;
delay_ms(10);
// Everything is ok
if (1) {
return YM2612_INIT_OK;
}
// An unspecified error
return YM2612_INIT_ERROR_UNSPECIFIED;
}
void ym2612_write(uint8_t reg, uint8_t part, uint8_t dat) {
// set data as output
*datadir = 0x00;
// set part
controlbus->a1 = part & YM2612_PART_2;
// select reg mode
controlbus->wr = 0;
controlbus->rd = 1;
controlbus->a0 = 0;
// cs low
controlbus->cs = 0;
// set data
*databus = reg;
// wait
delay_us(1);
// write data
controlbus->wr = 0;
controlbus->rd = 1;
// wait
delay_us(5);
// end write data
controlbus->wr = 1;
// wait
delay_us(5);
// cs high
controlbus->cs = 1;
// a0 high (write reg)
controlbus->a0 = 1;
// cs low
controlbus->cs = 0;
// set data
*databus = dat;
// wait
delay_us(1);
// write data
controlbus->wr = 0;
// wait
delay_us(5);
// write data
controlbus->wr = 1;
// wait
delay_us(5);
// cs high
controlbus->cs = 1;
// wait
delay_us(1);
}
uint8_t ym2612_read(uint8_t reg, uint8_t part) {
uint8_t dat;
// set data as input
*datadir = 0x00;
// set part
controlbus->a1 = part & YM2612_PART_2;
// select reg mode
controlbus->wr = 0;
controlbus->rd = 1;
controlbus->a0 = 0;
// cs low
controlbus->cs = 0;
// set data
*databus = reg;
// wait
delay_us(1);
// write data
controlbus->wr = 0;
controlbus->rd = 1;
// wait
delay_us(5);
// end write data
controlbus->wr = 1;
// wait
delay_us(5);
// cs high
controlbus->cs = 1;
// set data Direction
*datadir = 0xFF;
// a0 high (read reg)
controlbus->wr = 1;
controlbus->rd = 0;
controlbus->a0 = 1;
// cs low
controlbus->cs = 0;
// wait
delay_us(5);
// get data
dat = *databus;
// wait
delay_us(2);
// set data Direction
*datadir = 0x00;
// cs high
controlbus->cs = 1;
// wait
delay_us(1);
// return
return dat;
}
uint8_t ym2612_getLFO(){
return ym2612_read(YM2612_REG_LFO, YM2612_PART_1);
}
uint8_t ym2612_getChannel36(){
return ym2612_read(YM2612_REG_CH36MODE, YM2612_PART_1);
}
uint8_t ym2612_getDAC(){
return ym2612_read(YM2612_REG_DACENBL, YM2612_PART_1);
}
uint8_t ym2612_getDACData(){
return ym2612_read(YM2612_REG_DACDATA, YM2612_PART_1);
}
uint8_t ym2612_getOperatorFreq(uint8_t channel, uint8_t op){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_DETMUL + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return ym2612_read(addr, part);
}
void ym2612_getEnvelope(uint8_t channel, uint8_t op, ymenvelope_t* envelope){
// channel/op contribution to address
uint8_t daddr, part, attack, decay, sustain, release;
daddr = (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
// getting all registers
attack = ym2612_read(daddr + YM2612_REG_CH1OP1_RATEH, part);
decay = ym2612_read(daddr + YM2612_REG_CH1OP1_RATEMH, part);
sustain = ym2612_read(daddr + YM2612_REG_CH1OP1_RATEML, part);
release = ym2612_read(daddr + YM2612_REG_CH1OP1_RATEL, part);
// the total level
envelope->tl = YM2612_TL_MAX - (envelope->tl & YM2612_TL_MAX);
// fill attack registers
envelope->rs = attack >> 6;
envelope->ar = attack & 0x1F;
// fill decay registers
envelope->am = decay & YM2612_AM_ON;
envelope->d1r = decay & 0x1F;
// fill sustain registers
envelope->d2r = sustain & 0x1F;
// fill release
envelope->d1l = (release >> 4) & 0x0F;
envelope->rr = release & 0x0F;
}
uint8_t ym2612_getEnvelopeTotalLevel(uint8_t channel, uint8_t op){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_TL + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return YM2612_TL_MAX - (ym2612_read(addr, part) & YM2612_TL_MAX);
}
uint8_t ym2612_getEnvelopeAttack(uint8_t channel, uint8_t op){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEH + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return ym2612_read(addr, part);
}
uint8_t ym2612_getEnvelopeDecay(uint8_t channel, uint8_t op){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEMH + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return ym2612_read(addr, part);
}
uint8_t ym2612_getEnvelopeSustain(uint8_t channel, uint8_t op){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEML + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return ym2612_read(addr, part);
}
uint8_t ym2612_getEnvelopeRelease(uint8_t channel, uint8_t op){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEL + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return ym2612_read(addr, part);
}
uint16_t ym2612_getFrequency(uint8_t channel) {
uint8_t addrlow, part, datlow, dathigh;
addrlow = YM2612_REG_CH1_FREQL + (channel % 3);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
// read high THEN low
dathigh = ym2612_read(addrlow + 0x04, part);
datlow = ym2612_read(addrlow, part);
// return integer
return (uint16_t)(datahigh << 8) | dathigh;
}
uint16_t ym2612_getFrequency36(uint8_t channel, uint8_t op){
uint8_t addrlow, part, datlow, dathigh;
// check if channel is correct
if (channel != YM2612_CHANNEL_3 && channel != YM2612_CHANNEL_6) { return 0; }
// compute addr
addrlow = op != YM2612_OPERATOR_1 ? YM2612_REG_CH3OP2_FREQL - 1 + op : YM2612_REG_CH3OP1_FREQL;
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
// read high THEN low
dathigh = ym2612_read(addrlow + 0x04, part);
datlow = ym2612_read(addrlow, part);
// return integer
return (uint16_t)(datahigh << 8) | dathigh;
}
uint8_t ym2612_getAlgorithm(uint8_t channel){
uint8_t addr, part;
addr = YM2612_REG_CH1_ALGO + (channel % 3);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return ym2612_read(addr, part);
}
uint8_t ym2612_getStereoSensivity(uint8_t channel){
uint8_t addr, part;
addr = YM2612_REG_CH1_STEREOSENSIVITY + (channel % 3);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
return ym2612_read(addr, part);
}
void ym2612_setLFO(uint8_t enable, uint8_t frequency){
ym2612_write(YM2612_REG_LFO, YM2612_PART_1, (enable & YM2612_LFO_ON) | (frequency & 0x07));
}
void ym2612_setChannel36(uint8_t enable){
ym2612_write(YM2612_REG_CH36MODE, YM2612_PART_1, enable & 0xC0);
}
void ym2612_setKeyOnOff(uint8_t channel, uint8_t opmask){
channel = channel <= 3 ? channel : channel + 1;
ym2612_write(YM2612_REG_KEYONOFF, YM2612_PART_1, ((opmask & 0x0F) << 4) | (channel & 0x07));
}
void ym2612_setDAC(uint8_t enable){
ym2612_write(YM2612_REG_DACENBL, YM2612_PART_1, enable ? YM2612_DAC_ON : YM2612_DAC_ON);
}
void ym2612_setDACData(uint8_t dat){
ym2612_write(YM2612_REG_DACDATA, YM2612_PART_1, dat);
}
void ym2612_setOperatorFreq(uint8_t channel, uint8_t op, uint8_t freq){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_DETMUL + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
ym2612_write(addr, part, freq & 0x7F);
}
void ym2612_setEnvelope(uint8_t channel, uint8_t op, ymenvelope_t envelope){
uint8_t daddr, part;
daddr = (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
// TODO : envelope.tl must be computed in binary (faster?)
ym2612_write(daddr + YM2612_REG_CH1OP1_TL, part, YM2612_TL_MAX - (envelope.tl & YM2612_TL_MAX));
ym2612_write(daddr + YM2612_REG_CH1OP1_RATEH, part, ((envelope.rs & 0x03) << 6) | (envelope.ar & 0x1F));
ym2612_write(daddr + YM2612_REG_CH1OP1_RATEMH, part, (envelope.am & YM2612_AM_ON) | (envelope.d1r & 0x1F));
ym2612_write(daddr + YM2612_REG_CH1OP1_RATEML, part, envelope.d2r & 0x1F);
ym2612_write(daddr + YM2612_REG_CH1OP1_RATEL, part, (envelope.rr & 0x1F) | ((envelope.d1l & 0x1F) << 4));
}
void ym2612_setEnvelopeTotalLevel(uint8_t channel, uint8_t op, uint8_t level){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_TL + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
// TODO : envelope.tl must be computed in binary (faster?)
ym2612_write(addr, part, YM2612_TL_MAX - (level & YM2612_TL_MAX));
}
void ym2612_setEnvelopeAttack(uint8_t channel, uint8_t op, uint8_t ratescaling, uint8_t attackrate){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEH + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
ym2612_write(addr, part, ((ratescaling & 0x03) << 6) | (attackrate & 0x1F));
}
void ym2612_setEnvelopeDecay(uint8_t channel, uint8_t op, uint8_t am, uint8_t decayrate1){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEMH + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
ym2612_write(addr, part, (am & YM2612_AM_ON) | (decayrate1 & 0x1F));
}
void ym2612_setEnvelopeSustain(uint8_t channel, uint8_t op, uint8_t decayrate2){
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEML + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
ym2612_write(addr, part, decayrate2 & 0x1F);
}
void ym2612_setEnvelopeRelease(uint8_t channel, uint8_t op, uint8_t secondaryamplitude, uint8_t releaserate) {
uint8_t addr, part;
addr = YM2612_REG_CH1OP1_RATEL + (channel % 3) + (op * 4);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
ym2612_write(addr, part, (releaserate & 0x1F) | ((secondaryamplitude & 0x1F) << 4));
}
void ym2612_setFrequency(uint8_t channel, uint16_t frequency){
//TODO : how does frequency work?
uint8_t addrlow, part;
addrlow = YM2612_REG_CH1_FREQL + (channel % 3);
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
// write high THEN low
ym2612_write(addrlow + 0x04, part, (uint8_t)(frequency & 0xFF));
ym2612_write(addrlow, part, (uint8_t)((frequency >> 8) & 0x3F));
}
void ym2612_setFrequency36(uint8_t channel, uint8_t op, uint16_t frequency){
uint8_t addrlow, part;
//TODO : how does frequency work?
// check if channel is correct
if (channel != YM2612_CHANNEL_3 && channel != YM2612_CHANNEL_6) { return; }
// compute addr
addrlow = op != YM2612_OPERATOR_1 ? YM2612_REG_CH3OP2_FREQL - 1 + op : YM2612_REG_CH3OP1_FREQL;
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
// write high THEN low
ym2612_write(addrlow + 0x04, part, (uint8_t)(frequency & 0xFF));
ym2612_write(addrlow, part, (uint8_t)((frequency >> 8) & 0x3F));
}
void ym2612_setAlgorithm(uint8_t channel, uint8_t algorithm, uint8_t feedback){
uint8_t part;
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
ym2612_write(YM2612_REG_CH1_ALGO + (channel % 3), part, (algorithm & 0x07) | ((feedback & 0x07) << 3));
}
void ym2612_setStereoSensivity(uint8_t channel, uint8_t stereosensivity){
uint8_t part;
part = channel < 3 ? YM2612_PART_1 : YM2612_PART_2;
ym2612_write(YM2612_REG_CH1_STEREOSENSIVITY + (channel % 3), part, stereosensivity & 0xFB);
}
|
iLambda/ym2612-glue
|
inc/ym2612.h
|
<reponame>iLambda/ym2612-glue
#ifndef YM2612_INCLUDE_
#define YM2612_INCLUDE_
#ifndef NULL
#define NULL 0
#endif
#include <xc.h>
#include <stdint.h>
#include <stdlib.h>
/*
* REGISTERS & COMMANDS
*/
// HARDWARE COMMANDS
#define YM2612_CMD_SELREG1 0x08
#define YM2612_CMD_WRTREG1 0x0A
#define YM2612_CMD_REDREG1 0x06
#define YM2612_CMD_SELREG2 0x09
#define YM2612_CMD_WRTREG2 0x0B
#define YM2612_CMD_REDREG2 0x07
#define YM2612_CMD_HIGHIMP 0x10
// CHIP PART
#define YM2612_PART_1 0x00
#define YM2612_PART_2 0x01
// COMMON REGISTERS
#define YM2612_REG_LFO 0x22
#define YM2612_REG_LFOENABLE 0x22
#define YM2612_REG_LFOFREQ 0x22
#define YM2612_REG_TIMERAH 0x24
#define YM2612_REG_TIMERAL 0x25
#define YM2612_REG_TIMERB 0x26
#define YM2612_REG_CH36MODE 0x27
#define YM2612_REG_KEYONOFF 0x28
#define YM2612_REG_DACDATA 0x2A
#define YM2612_REG_DACENBL 0x2B
// OP1 REGISTERS
// CH1 REGISTERS
#define YM2612_REG_CH1OP1_DETMUL 0x30
#define YM2612_REG_CH1OP1_DT1 0x30
#define YM2612_REG_CH1OP1_MUL 0x30
#define YM2612_REG_CH1OP1_TL 0x40
#define YM2612_REG_CH1OP1_RATEH 0x50
#define YM2612_REG_CH1OP1_RS 0x50
#define YM2612_REG_CH1OP1_AR 0x50
#define YM2612_REG_CH1OP1_RATEMH 0x60
#define YM2612_REG_CH1OP1_AM 0x60
#define YM2612_REG_CH1OP1_D1R 0x60
#define YM2612_REG_CH1OP1_RATEML 0x70
#define YM2612_REG_CH1OP1_D2R 0x70
#define YM2612_REG_CH1OP1_RATEL 0x80
#define YM2612_REG_CH1OP1_D1L 0x80
#define YM2612_REG_CH1OP1_RR 0x80
#define YM2612_REG_CH1OP1_UNDEF 0x90
// CH2 REGISTERS
#define YM2612_REG_CH2OP1_DETMUL 0x31
#define YM2612_REG_CH2OP1_DT1 0x31
#define YM2612_REG_CH2OP1_MUL 0x31
#define YM2612_REG_CH2OP1_TOTLVL 0x41
#define YM2612_REG_CH2OP1_TL 0x41
#define YM2612_REG_CH2OP1_RATEH 0x51
#define YM2612_REG_CH2OP1_RS 0x51
#define YM2612_REG_CH2OP1_AR 0x51
#define YM2612_REG_CH2OP1_RATEMH 0x61
#define YM2612_REG_CH2OP1_AM 0x61
#define YM2612_REG_CH2OP1_D1R 0x61
#define YM2612_REG_CH2OP1_RATEML 0x71
#define YM2612_REG_CH2OP1_D2R 0x71
#define YM2612_REG_CH2OP1_RATEL 0x81
#define YM2612_REG_CH2OP1_D1L 0x81
#define YM2612_REG_CH2OP1_RR 0x81
#define YM2612_REG_CH2OP1_UNDEF 0x91
// CH3 REGISTERS
#define YM2612_REG_CH3OP1_DETMUL 0x32
#define YM2612_REG_CH3OP1_DT1 0x32
#define YM2612_REG_CH3OP1_MUL 0x32
#define YM2612_REG_CH3OP1_TOTLVL 0x42
#define YM2612_REG_CH3OP1_TL 0x42
#define YM2612_REG_CH3OP1_RATEH 0x52
#define YM2612_REG_CH3OP1_RS 0x52
#define YM2612_REG_CH3OP1_AR 0x52
#define YM2612_REG_CH3OP1_RATEMH 0x62
#define YM2612_REG_CH3OP1_AM 0x62
#define YM2612_REG_CH3OP1_D1R 0x62
#define YM2612_REG_CH3OP1_RATEML 0x72
#define YM2612_REG_CH3OP1_D2R 0x72
#define YM2612_REG_CH3OP1_RATEL 0x82
#define YM2612_REG_CH3OP1_D1L 0x82
#define YM2612_REG_CH3OP1_RR 0x82
#define YM2612_REG_CH3OP1_UNDEF 0x92
// OP2 REGISTERS
// CH1 REGISTERS
#define YM2612_REG_CH1OP2_DETMUL 0x34
#define YM2612_REG_CH1OP2_DT1 0x34
#define YM2612_REG_CH1OP2_MUL 0x34
#define YM2612_REG_CH1OP2_TOTLVL 0x44
#define YM2612_REG_CH1OP2_TL 0x44
#define YM2612_REG_CH1OP2_RATEH 0x54
#define YM2612_REG_CH1OP2_RS 0x54
#define YM2612_REG_CH1OP2_AR 0x54
#define YM2612_REG_CH1OP2_RATEMH 0x64
#define YM2612_REG_CH1OP2_AM 0x64
#define YM2612_REG_CH1OP2_D1R 0x64
#define YM2612_REG_CH1OP2_RATEML 0x74
#define YM2612_REG_CH1OP2_D2R 0x74
#define YM2612_REG_CH1OP2_RATEL 0x84
#define YM2612_REG_CH1OP2_D1L 0x84
#define YM2612_REG_CH1OP2_RR 0x84
#define YM2612_REG_CH1OP2_UNDEF 0x94
// CH2 REGISTERS
#define YM2612_REG_CH2OP2_DETMUL 0x35
#define YM2612_REG_CH2OP2_DT1 0x35
#define YM2612_REG_CH2OP2_MUL 0x35
#define YM2612_REG_CH2OP2_TOTLVL 0x45
#define YM2612_REG_CH2OP2_TL 0x45
#define YM2612_REG_CH2OP2_RATEH 0x55
#define YM2612_REG_CH2OP2_RS 0x55
#define YM2612_REG_CH2OP2_AR 0x55
#define YM2612_REG_CH2OP2_RATEMH 0x65
#define YM2612_REG_CH2OP2_AM 0x65
#define YM2612_REG_CH2OP2_D1R 0x65
#define YM2612_REG_CH2OP2_RATEML 0x75
#define YM2612_REG_CH2OP2_D2R 0x75
#define YM2612_REG_CH2OP2_RATEL 0x85
#define YM2612_REG_CH2OP2_D1L 0x85
#define YM2612_REG_CH2OP2_RR 0x85
#define YM2612_REG_CH2OP2_UNDEF 0x95
// CH3 REGISTERS
#define YM2612_REG_CH3OP2_DETMUL 0x36
#define YM2612_REG_CH3OP2_DT1 0x36
#define YM2612_REG_CH3OP2_MUL 0x36
#define YM2612_REG_CH3OP2_TOTLVL 0x46
#define YM2612_REG_CH3OP2_TL 0x46
#define YM2612_REG_CH3OP2_RATEH 0x56
#define YM2612_REG_CH3OP2_RS 0x56
#define YM2612_REG_CH3OP2_AR 0x56
#define YM2612_REG_CH3OP2_RATEMH 0x66
#define YM2612_REG_CH3OP2_AM 0x66
#define YM2612_REG_CH3OP2_D1R 0x66
#define YM2612_REG_CH3OP2_RATEML 0x76
#define YM2612_REG_CH3OP2_D2R 0x76
#define YM2612_REG_CH3OP2_RATEL 0x86
#define YM2612_REG_CH3OP2_D1L 0x86
#define YM2612_REG_CH3OP2_RR 0x86
#define YM2612_REG_CH3OP2_UNDEF 0x96
// OP3 REGISTERS
// CH1 REGISTERS
#define YM2612_REG_CH1OP3_DETMUL 0x38
#define YM2612_REG_CH1OP3_DT1 0x38
#define YM2612_REG_CH1OP3_MUL 0x38
#define YM2612_REG_CH1OP3_TOTLVL 0x48
#define YM2612_REG_CH1OP3_TL 0x48
#define YM2612_REG_CH1OP3_RATEH 0x58
#define YM2612_REG_CH1OP3_RS 0x58
#define YM2612_REG_CH1OP3_AR 0x58
#define YM2612_REG_CH1OP3_RATEMH 0x68
#define YM2612_REG_CH1OP3_AM 0x68
#define YM2612_REG_CH1OP3_D1R 0x68
#define YM2612_REG_CH1OP3_RATEML 0x78
#define YM2612_REG_CH1OP3_D2R 0x78
#define YM2612_REG_CH1OP3_RATEL 0x88
#define YM2612_REG_CH1OP3_D1L 0x88
#define YM2612_REG_CH1OP3_RR 0x88
#define YM2612_REG_CH1OP3_UNDEF 0x98
// CH2 REGISTERS
#define YM2612_REG_CH2OP3_DETMUL 0x39
#define YM2612_REG_CH2OP3_DT1 0x39
#define YM2612_REG_CH2OP3_MUL 0x39
#define YM2612_REG_CH2OP3_TOTLVL 0x49
#define YM2612_REG_CH2OP3_TL 0x49
#define YM2612_REG_CH2OP3_RATEH 0x59
#define YM2612_REG_CH2OP3_RS 0x59
#define YM2612_REG_CH2OP3_AR 0x59
#define YM2612_REG_CH2OP3_RATEMH 0x69
#define YM2612_REG_CH2OP3_AM 0x69
#define YM2612_REG_CH2OP3_D1R 0x69
#define YM2612_REG_CH2OP3_RATEML 0x79
#define YM2612_REG_CH2OP3_D2R 0x79
#define YM2612_REG_CH2OP3_RATEL 0x89
#define YM2612_REG_CH2OP3_D1L 0x89
#define YM2612_REG_CH2OP3_RR 0x89
#define YM2612_REG_CH2OP3_UNDEF 0x99
// CH3 REGISTERS
#define YM2612_REG_CH3OP3_DETMUL 0x3A
#define YM2612_REG_CH3OP3_DT1 0x3A
#define YM2612_REG_CH3OP3_MUL 0x3A
#define YM2612_REG_CH3OP3_TOTLVL 0x4A
#define YM2612_REG_CH3OP3_TL 0x4A
#define YM2612_REG_CH3OP3_RATEH 0x5A
#define YM2612_REG_CH3OP3_RS 0x5A
#define YM2612_REG_CH3OP3_AR 0x5A
#define YM2612_REG_CH3OP3_RATEMH 0x6A
#define YM2612_REG_CH3OP3_AM 0x6A
#define YM2612_REG_CH3OP3_D1R 0x6A
#define YM2612_REG_CH3OP3_RATEML 0x7A
#define YM2612_REG_CH3OP3_D2R 0x7A
#define YM2612_REG_CH3OP3_RATEL 0x8A
#define YM2612_REG_CH3OP3_D1L 0x8A
#define YM2612_REG_CH3OP3_RR 0x8A
#define YM2612_REG_CH3OP3_UNDEF 0x9A
// OP4 REGISTERS
// CH1 REGISTERS
#define YM2612_REG_CH1OP4_DETMUL 0x3C
#define YM2612_REG_CH1OP4_DT1 0x3C
#define YM2612_REG_CH1OP4_MUL 0x3C
#define YM2612_REG_CH1OP4_TOTLVL 0x4C
#define YM2612_REG_CH1OP4_TL 0x4C
#define YM2612_REG_CH1OP4_RATEH 0x5C
#define YM2612_REG_CH1OP4_RS 0x5C
#define YM2612_REG_CH1OP4_AR 0x5C
#define YM2612_REG_CH1OP4_RATEMH 0x6C
#define YM2612_REG_CH1OP4_AM 0x6C
#define YM2612_REG_CH1OP4_D1R 0x6C
#define YM2612_REG_CH1OP4_RATEML 0x7C
#define YM2612_REG_CH1OP4_D2R 0x7C
#define YM2612_REG_CH1OP4_RATEL 0x8C
#define YM2612_REG_CH1OP4_D1L 0x8C
#define YM2612_REG_CH1OP4_RR 0x8C
#define YM2612_REG_CH1OP4_UNDEF 0x9C
// CH2 REGISTERS
#define YM2612_REG_CH2OP4_DETMUL 0x3D
#define YM2612_REG_CH2OP4_DT1 0x3D
#define YM2612_REG_CH2OP4_MUL 0x3D
#define YM2612_REG_CH2OP4_TOTLVL 0x4D
#define YM2612_REG_CH2OP4_TL 0x4D
#define YM2612_REG_CH2OP4_RATEH 0x5D
#define YM2612_REG_CH2OP4_RS 0x5D
#define YM2612_REG_CH2OP4_AR 0x5D
#define YM2612_REG_CH2OP4_RATEMH 0x6D
#define YM2612_REG_CH2OP4_AM 0x6D
#define YM2612_REG_CH2OP4_D1R 0x6D
#define YM2612_REG_CH2OP4_RATEML 0x7D
#define YM2612_REG_CH2OP4_D2R 0x7D
#define YM2612_REG_CH2OP4_RATEL 0x8D
#define YM2612_REG_CH2OP4_D1L 0x8D
#define YM2612_REG_CH2OP4_RR 0x8D
#define YM2612_REG_CH2OP4_UNDEF 0x9D
// CH3 REGISTERS
#define YM2612_REG_CH3OP4_DETMUL 0x3E
#define YM2612_REG_CH3OP4_DT1 0x3E
#define YM2612_REG_CH3OP4_MUL 0x3E
#define YM2612_REG_CH3OP4_TOTLVL 0x4E
#define YM2612_REG_CH3OP4_TL 0x4E
#define YM2612_REG_CH3OP4_RATEH 0x5E
#define YM2612_REG_CH3OP4_RS 0x5E
#define YM2612_REG_CH3OP4_AR 0x5E
#define YM2612_REG_CH3OP4_RATEMH 0x6E
#define YM2612_REG_CH3OP4_AM 0x6E
#define YM2612_REG_CH3OP4_D1R 0x6E
#define YM2612_REG_CH3OP4_RATEML 0x7E
#define YM2612_REG_CH3OP4_D2R 0x7E
#define YM2612_REG_CH3OP4_RATEL 0x8E
#define YM2612_REG_CH3OP4_D1L 0x8E
#define YM2612_REG_CH3OP4_RR 0x8E
#define YM2612_REG_CH3OP4_UNDEF 0x9E
// CH1-3 REGISTERS
#define YM2612_REG_CH1_FREQL 0xA0
#define YM2612_REG_CH1_FREQH 0xA4
#define YM2612_REG_CH2_FREQL 0xA1
#define YM2612_REG_CH2_FREQH 0xA5
#define YM2612_REG_CH3_FREQL 0xA2
#define YM2612_REG_CH3_FREQH 0xA6
#define YM2612_REG_CH3OP1_FREQL 0xA2
#define YM2612_REG_CH3OP1_FREQH 0xA6
#define YM2612_REG_CH3OP2_FREQL 0xA8
#define YM2612_REG_CH3OP2_FREQH 0xAC
#define YM2612_REG_CH3OP3_FREQL 0xA9
#define YM2612_REG_CH3OP3_FREQH 0xAD
#define YM2612_REG_CH3OP4_FREQL 0xAA
#define YM2612_REG_CH3OP4_FREQH 0xAE
// ALGORITHMS
#define YM2612_REG_CH1_ALGO 0xB0
#define YM2612_REG_CH2_ALGO 0xB1
#define YM2612_REG_CH3_ALGO 0xB2
// STEREOSENSIVITY
#define YM2612_REG_CH1_STEREOSENSIVITY 0xB4
#define YM2612_REG_CH2_STEREOSENSIVITY 0xB5
#define YM2612_REG_CH3_STEREOSENSIVITY 0xB6
/*
* FLAGS
*/
#define YM2612_D1R 0x1F
#define YM2612_D2R 0x1F
#define YM2612_D1L 0xF0
#define YM2612_RR 0x0F
#define YM2612_CHANNEL_1 0x00
#define YM2612_CHANNEL_2 0x01
#define YM2612_CHANNEL_3 0x02
#define YM2612_CHANNEL_4 0x03
#define YM2612_CHANNEL_5 0x04
#define YM2612_CHANNEL_6 0x05
#define YM2612_OPERATOR_1 0x00
#define YM2612_OPERATOR_2 0x01
#define YM2612_OPERATOR_3 0x02
#define YM2612_OPERATOR_4 0x03
#define YM2612_OPERATORMASK_1 0x01
#define YM2612_OPERATORMASK_2 0x02
#define YM2612_OPERATORMASK_3 0x04
#define YM2612_OPERATORMASK_4 0x08
#define YM2612_OPERATORMASK_NONE 0x00
#define YM2612_OPERATORMASK_ALL YM2612_OPERATOR_1 | \
YM2612_OPERATOR_2 | \
YM2612_OPERATOR_3 | \
YM2612_OPERATOR_4
#define YM2612_LFO_ON 0x08
#define YM2612_LFO_OFF 0x00
#define YM2612_LFO_398 0x00
#define YM2612_LFO_556 0x01
#define YM2612_LFO_602 0x02
#define YM2612_LFO_637 0x03
#define YM2612_LFO_688 0x04
#define YM2612_LFO_963 0x05
#define YM2612_LFO_4810 0x06
#define YM2612_LFO_7220 0x07
#define YM2612_CH36_ON 0x40
#define YM2612_CH36_OFF 0x00
#define YM2612_DAC_ON 0xFF
#define YM2612_DAC_OFF 0x00
#define YM2612_FREQ_DETUNE_1 0x00
#define YM2612_FREQ_DETUNE_1PE 0x10
#define YM2612_FREQ_DETUNE_1P2E 0x20
#define YM2612_FREQ_DETUNE_1P3E 0x30
#define YM2612_FREQ_DETUNE_1ME 0x50
#define YM2612_FREQ_DETUNE_1M2E 0x60
#define YM2612_FREQ_DETUNE_1M3E 0x70
#define YM2612_FREQ_MUL_HALF 0x00
#define YM2612_FREQ_MUL_1 0x01
#define YM2612_FREQ_MUL_2 0x02
#define YM2612_FREQ_MUL_3 0x03
#define YM2612_FREQ_MUL_4 0x04
#define YM2612_FREQ_MUL_5 0x05
#define YM2612_FREQ_MUL_6 0x06
#define YM2612_FREQ_MUL_7 0x07
#define YM2612_FREQ_MUL_8 0x08
#define YM2612_FREQ_MUL_9 0x09
#define YM2612_FREQ_MUL_10 0x0A
#define YM2612_FREQ_MUL_11 0x0B
#define YM2612_FREQ_MUL_12 0x0C
#define YM2612_FREQ_MUL_13 0x0D
#define YM2612_FREQ_MUL_14 0x0E
#define YM2612_FREQ_MUL_15 0x0F
#define YM2612_TL_MIN 0x00
#define YM2612_TL_MAX 0x7F
#define YM2612_RS_MIN 0x00
#define YM2612_RS_8 0x00
#define YM2612_RS_4 0x01
#define YM2612_RS_2 0x02
#define YM2612_RS_1 0x03
#define YM2612_RS_MAX 0x03
#define YM2612_AM_ON 0x80
#define YM2612_AM_OFF 0x00
#define YM2612_OP_FEEDBACK 0b111000
#define YM2612_OP_ALGORITHM 0b111
#define YM2612_STEREO_L 0x80
#define YM2612_STEREO_R 0x40
#define YM2612_STEREO_LR YM2612_STEREO_L | YM2612_STEREO_R
#define YM2612_AMS_0 0x00
#define YM2612_AMS_14 0x01
#define YM2612_AMS_59 0x02
#define YM2612_AMS_118 0x03
#define YM2612_FMS_0 0x00
#define YM2612_FMS_34 0x01
#define YM2612_FMS_67 0x02
#define YM2612_FMS_100 0x03
#define YM2612_FMS_140 0x04
#define YM2612_FMS_200 0x05
#define YM2612_FMS_400 0x06
#define YM2612_FMS_800 0x07
/*
* ERROR CODES
*/
#define YM2612_INIT_OK 0x00
#define YM2612_INIT_ERROR_UNSPECIFIED 0xFF
/*
* STRUCTS
*/
typedef struct {
cs : 1, wr : 1, rd : 1,
a0 : 1, a1 : 1,
ic : 1;
} ymcontrolbus_t;
typedef struct ymenvelope_t {
// the total level. <128
uint8_t tl;
// the rate scaling
uint8_t rs;
// the attack rate
uint8_t ar;
// the first decay rate
uint8_t d1r;
// amplitude modulation enable
uint8_t am;
// secondary decay rate
uint8_t d2r;
// secondary amplitude
uint8_t d1l;
// release rate
uint8_t rr;
} ymenvelope_t;
static uint8_t* controldir = NULL;
static ymcontrolbus_t* controlbus = NULL;
static uint8_t* databus = NULL;
static uint8_t* datadir = NULL;
uint8_t ym2612_init(uint8_t* controlbus, uint8_t* controldir, uint8_t* databus, uint8_t* datadir);
void ym2612_write(uint8_t reg, uint8_t part, uint8_t dat);
uint8_t ym2612_read(uint8_t reg, uint8_t part);
uint8_t ym2612_getLFO();
uint8_t ym2612_getChannel36();
uint8_t ym2612_getDAC();
uint8_t ym2612_getDACData();
uint8_t ym2612_getOperatorFreq(uint8_t channel, uint8_t op);
void ym2612_getEnvelope(uint8_t channel, uint8_t op, ymenvelope_t* envelope);
uint8_t ym2612_getEnvelopeTotalLevel(uint8_t channel, uint8_t op);
uint8_t ym2612_getEnvelopeAttack(uint8_t channel, uint8_t op);
uint8_t ym2612_getEnvelopeDecay(uint8_t channel, uint8_t op);
uint8_t ym2612_getEnvelopeSustain(uint8_t channel, uint8_t op);
uint8_t ym2612_getEnvelopeRelease(uint8_t channel, uint8_t op);
uint16_t ym2612_getFrequency(uint8_t channel);
uint16_t ym2612_getFrequency36(uint8_t channel, uint8_t op);
uint8_t ym2612_getAlgorithm(uint8_t channel);
uint8_t ym2612_getStereoSensivity(uint8_t channel);
void ym2612_setLFO(uint8_t enable, uint8_t frequency);
void ym2612_setChannel36(uint8_t enable);
void ym2612_setKeyOnOff(uint8_t channel, uint8_t operatormask);
void ym2612_setDAC(uint8_t enable);
void ym2612_setDACData(uint8_t dat);
void ym2612_setOperatorFreq(uint8_t channel, uint8_t op, uint8_t freq);
void ym2612_setEnvelope(uint8_t channel, uint8_t op, ymenvelope_t envelope);
void ym2612_setEnvelopeTotalLevel(uint8_t channel, uint8_t op, uint8_t level);
void ym2612_setEnvelopeAttack(uint8_t channel, uint8_t op, uint8_t ratescaling, uint8_t attackrate);
void ym2612_setEnvelopeDecay(uint8_t channel, uint8_t op, uint8_t am, uint8_t decayrate1);
void ym2612_setEnvelopeSustain(uint8_t channel, uint8_t op, uint8_t decayrate2);
void ym2612_setEnvelopeRelease(uint8_t channel, uint8_t op, uint8_t secondaryamplitude, uint8_t releaserate);
void ym2612_setFrequency(uint8_t channel, uint16_t frequency);
void ym2612_setFrequency36(uint8_t channel, uint8_t op, uint16_t frequency);
void ym2612_setAlgorithm(uint8_t channel, uint8_t algorithm, uint8_t feedback);
void ym2612_setStereoSensivity(uint8_t channel, uint8_t stereosensivity);
#endif
|
iHamburg/FZSoundManager
|
BLCloudStoreSoundManager/BLCloudStoreSoundManager/BLSMessageSoundPlayManager.h
|
//
// BLSMessageSoundPlayManager.h
// BLCloudStoreSoundManager
//
// Created by 张怡清 on 2017/8/16.
// Copyright © 2017年 BLS. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface BLSMessageSoundPlayManager : NSObject
+ (instancetype)sharedInstance;
/*
* 根据type播放语音文件
*/
-(void)playMessageSoundWithType:(NSInteger)type;
@end
|
samuliL/raytracer
|
src/rtscene.h
|
<filename>src/rtscene.h
#ifndef __RTSCENE_H_INCLUDED__
#define __RTSCENE_H_INCLUDED__
#include "rtcamera.h"
#include "rtcanvas.h"
#include "rtobjects.h"
class RTScene{
private:
vector<RTObject*> object_list;
//vector<RTLightSource> lights_list;
RTCamera camera;
public:
RTScene();
~RTScene();
void setCamera(RTVector &loc, RTVector &dir);
void addObject(RTObject *rto);
// implementations of two different rendering systems
RTCanvas renderSpherical(int xSize, int ySize);
RTCanvas renderPlanar(int xSize, int ySize);
// function pointer to the actual rendering function
RTCanvas (RTScene::*renderFunction)(int, int);
RTCanvas render(int xSize, int ySize){ return (*this.*renderFunction)(xSize, ySize); }
RGBValue shootRay(RTVector &loc, RTVector &dir);
};
#endif
|
samuliL/raytracer
|
src/rtvector.h
|
#ifndef __RTVECTOR_H_INCLUDED__
#define __RTVECTOR_H_INCLUDED__
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
using namespace std;
const double PI = 3.14159265;
class RTVector {
private:
double x, y, z;
public:
double getX() const {return x;}
double getY() const {return y;}
double getZ() const {return z;}
double getTheta() const {return acos(z/sqrt(x*x+y*y+z*z));}
double getPhi() const;
double dot(RTVector &v) const {return x*v.getX() + y*v.getY() + z*v.getZ();}
double norm(){return sqrt(x*x+y*y+z*z);}
RTVector operator+(const RTVector& v) const;
RTVector operator-(const RTVector& v) const;
RTVector operator*(double c) const;
void normalize() {double r = sqrt(x*x+y*y+z*z); x = x/r; y = y/r; z = z/r;}
void scale(double s) {x = x*s; y = y*s; z = z*s;}
void set(RTVector &v) {setXYZ(v.getX(), v.getY(), v.getZ());}
void setXYZ(double x_, double y_, double z_) {x = x_; y = y_; z = z_;}
RTVector() {}
RTVector(double x_, double y_, double z_) {setXYZ(x_, y_, z_);}
RTVector getCopy() const;
void rotateBy(double dphi, double dtheta_);
void print() {cout << "x: " << x << " y: " << y << " z: " << z << " phi: " << acos(x/sqrt(x*x+y*y)) << " theta: " << acos(z/sqrt(x*x + y*y + z*z)) << endl;};
};
#endif
|
samuliL/raytracer
|
src/rtobjects.h
|
<filename>src/rtobjects.h
#ifndef __RTOBJECTS_H_INCLUDED__
#define __RTOBJECTS_H_INCLUDED__
#include "rtvector.h"
#include "rgbvalue.h"
class RTObject{
protected:
RTVector location;
double reflectionRate; // value between 0.0 and 1.0, 0.0 - does not reflect light, 1.0 reflects everything
RGBValue color;
public:
RTObject() {}
RTObject(double x, double y, double z) {location.setXYZ(x, y, z);}
virtual ~RTObject() {};
virtual double checkCollision(RTVector &rayLoc, RTVector &rayDir) = 0;// {return -1.0;}
virtual bool isReflective() = 0;
virtual vector<RTVector> getReflection(RTVector &loc, RTVector &dir) = 0;
virtual RGBValue getColor(RTVector &loc, RTVector &dir) {return RGBValue(0, 0, 0);};
};
class RTCube : public RTObject{
// implementation of this class is incomplete and cannot be used
private:
double side;
vector<RTVector> vertices;
vector<double> sideConst; // each side of the cube is defined by an equation <normal, point> = sideconstant
vector<RTVector> normals; // normal vectors of the sides
// keep track where ray hits the cube when checking collision
int sideRayHit;
RTVector pointRayHit;
public:
static const int sides[6][4]; // array that associates vertices of the cube with the sides of the cube
~RTCube() {return;};
RTCube(RTVector &location, double side_length);
double getSideLength() {return side;}
void initializeSides();
double checkCollision(RTVector &rayLoc, RTVector &rayDir);
bool insideTriangle(RTVector point, RTVector v1, RTVector v2, RTVector v3);
bool isReflective() {return false;}
RGBValue getColor(RTVector &loc, RTVector &dir);
virtual vector<RTVector> getReflection(RTVector &loc, RTVector &dir) {return vector<RTVector>();}
};
class RTSphere : public RTObject{
private:
double radius;
public:
RTSphere(RTVector &location, double radius);
~RTSphere() {return;};
double getRadius(){return radius;}
double checkCollision(RTVector &rayLoc, RTVector &rayDir);
vector<RTVector> getReflection(RTVector &loc, RTVector &dir);
bool isReflective() {return true;}
};
class RTGround : public RTObject{
double checkCollision(RTVector &rayLoc, RTVector &rayDir);
vector<RTVector> getReflection(RTVector &loc, RTVector &dir) {vector<RTVector> r; return r;};
bool isReflective() {return false;}
RGBValue getColor(RTVector &loc, RTVector &dir);
};
#endif
|
samuliL/raytracer
|
src/rgbvalue.h
|
#ifndef __RGBVALUE_H_INCLUDED__
#define __RGBVALUE_H_INCLUDED__
using namespace std;
class RGBValue {
private:
unsigned char red, green, blue;
public:
unsigned char getRed() {return red;}
unsigned char getGreen() {return green;}
unsigned char getBlue() {return blue;}
RGBValue(unsigned char r, unsigned char g, unsigned char b) { setRGB(r, g, b); }
RGBValue() {setRGB(0, 0, 0);}
void setRGB(unsigned char r, unsigned char g, unsigned char b) { red = r; green = g; blue = b;}
};
#endif
|
samuliL/raytracer
|
src/rtcamera.h
|
#ifndef __RTCAMERA_H_INCLUDED__
#define __RTCAMERA_H_INCLUDED__
#include "rtvector.h"
class RTCamera{
private:
RTVector location;
RTVector direction;
double lensCurvature; // value between 0.0 and 1.0, 0.0 no curvature, 1.0 maximal curvature
double lensSize;
public:
RTCamera();
RTCamera(RTVector &loc, RTVector &dir, double lc, double ls);
void setLensCurvature(double d) {lensCurvature = d;}
double getLensCurvature() {return lensCurvature;}
void setLensSize(double ls) {lensSize = ls;}
double getLensSize() {return lensSize;}
void setLocation(RTVector &loc) {location.set(loc);}
void setDirection(RTVector &dir) {dir.normalize(); direction.set(dir);}
RTVector getLocation() {return location.getCopy();}
RTVector getDirection() {return direction.getCopy();}
// returns orthogonal basis vectors for the plane perpendicular to the camera direction
vector<RTVector> getLensBasis();
};
#endif
|
samuliL/raytracer
|
src/rtcanvas.h
|
#ifndef __RTCANVAS_H_INCLUDED__
#define __RTCANVAS_H_INCLUDED__
#include "rgbvalue.h"
class RTCanvas{
private:
int xSize, ySize;
RGBValue *colors;
public:
int getXSize() {return xSize;}
RTCanvas(const int xS, const int yS);
~RTCanvas();
RGBValue *getCol(int x, int y);
void setCol(int x, int y, RGBValue c);
void saveCanvas(const char *filename);
};
#endif
|
roddyyaga/ocaml-zmq
|
zmq/src/msg.h
|
<reponame>roddyyaga/ocaml-zmq
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#ifndef CAML_ZMQ_MSG_H_
#define CAML_ZMQ_MSG_H_
#include <caml/mlvalues.h>
#define CAML_ZMQ_Msg_val(v) (*((void **) Data_custom_val(v)))
value caml_zmq_copy_msg(void *zmq_msg);
#endif /* CAML_ZMQ_MSG_H_ */
|
roddyyaga/ocaml-zmq
|
zmq/src/msg.c
|
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#include "msg.h"
#include <caml/custom.h>
#include <caml/memory.h>
#include <zmq.h>
static void custom_finalize_msg(value msg) {
if (CAML_ZMQ_Msg_val(msg)) {
zmq_msg_close(CAML_ZMQ_Msg_val(msg));
free(CAML_ZMQ_Msg_val(msg));
CAML_ZMQ_Msg_val(msg) = NULL;
}
}
static struct custom_operations caml_zmq_msg_ops = {
"org.zeromq.msg",
custom_finalize_msg,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default
#ifdef custom_compare_ext_default
, custom_compare_ext_default
#endif
#ifdef custom_fixed_length_default
, custom_fixed_length_default
#endif
};
value caml_zmq_copy_msg(void *zmq_msg) {
CAMLparam0 ();
CAMLlocal1 (msg);
msg = caml_alloc_custom(&caml_zmq_msg_ops, sizeof (zmq_msg), 0, 1);
CAML_ZMQ_Msg_val(msg) = zmq_msg;
CAMLreturn (msg);
}
|
roddyyaga/ocaml-zmq
|
zmq/src/socket.c
|
<gh_stars>10-100
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#include "socket.h"
#include "fail.h"
#include <caml/memory.h>
#include <caml/custom.h>
#include <caml/alloc.h>
#include <zmq.h>
static void custom_finalize_socket(value socket) {
if (CAML_ZMQ_Socket_val(socket)) {
fprintf(stderr, "Error: Socket not closed before finalization\n");
}
}
static struct custom_operations caml_zmq_socket_ops = {
"org.zeromq.socket",
custom_finalize_socket,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default
#ifdef custom_compare_ext_default
, custom_compare_ext_default
#endif
#ifdef custom_fixed_length_default
, custom_fixed_length_default
#endif
};
/* Captures a reference to the context to avoid collecting it prematurely */
value caml_zmq_copy_socket(void *zmq_socket) {
CAMLparam0 ();
CAMLlocal1 (socket);
socket = caml_alloc_custom(&caml_zmq_socket_ops, sizeof (zmq_socket), 0, 1);
CAML_ZMQ_Socket_val(socket) = zmq_socket;
CAMLreturn (socket);
}
|
roddyyaga/ocaml-zmq
|
zmq/src/poll.h
|
<filename>zmq/src/poll.h
#ifndef CAML_ZMQ_POLL_H_
#define CAML_ZMQ_POLL_H_
#include <caml/mlvalues.h>
#include <zmq.h>
struct caml_zmq_poll {
zmq_pollitem_t *poll_items;
int num_elems;
};
#define CAML_ZMQ_Poll_val(v) ((struct caml_zmq_poll *) Data_custom_val(v))
value caml_zmq_poll_of_pollitem_array(value pollitem_array);
value caml_zmq_poll(value poll, value timeout);
value CAML_ZMQ_Val_mask(short mask);
short CAML_ZMQ_Mask_val(value mask);
#endif /* CAML_ZMQ_POLLSET_H_ */
|
roddyyaga/ocaml-zmq
|
zmq/src/caml_zmq_stubs.c
|
<gh_stars>10-100
/*
* Copyright (C) 2011 <NAME> and contributors
*/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
#include <caml/mlvalues.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/callback.h>
#include <caml/memory.h>
#include <caml/custom.h>
#include <caml/intext.h>
#include <caml/threads.h>
#include <caml/bigarray.h>
#if defined(_WIN32) || defined(_WIN64)
# include <winsock2.h>
# include <windows.h>
# define fd_type SOCKET
# define Val_fd(x) win_alloc_socket(x)
#else
# define fd_type int
# define Val_fd(x) Val_int(x)
#endif
#include <zmq.h>
#if ZMQ_VERSION_MAJOR != 4
#error "This library requires libzmq 4.x"
#endif
#include "fail.h"
#include "context.h"
#include "socket.h"
#include "msg.h"
#include <uint64.h>
/**
* Version
*/
CAMLprim value caml_zmq_version(value unit) {
CAMLparam1 (unit);
CAMLlocal1 (version_tuple);
int major, minor, patch;
zmq_version(&major, &minor, &patch);
version_tuple = caml_alloc_tuple(3);
Store_field(version_tuple, 0, Val_int(major));
Store_field(version_tuple, 1, Val_int(minor));
Store_field(version_tuple, 2, Val_int(patch));
CAMLreturn (version_tuple);
}
/**
* Init
*/
CAMLprim value caml_zmq_new(value unit) {
CAMLparam1 (unit);
CAMLlocal1 (ctx_value);
void *ctx = zmq_ctx_new();
caml_zmq_raise_if(ctx == NULL, "zmq_ctx_new");
ctx_value = caml_zmq_copy_context(ctx);
CAMLreturn (ctx_value);
}
/**
* Term
*/
CAMLprim value caml_zmq_term(value ctx) {
CAMLparam1 (ctx);
int result = zmq_ctx_term(CAML_ZMQ_Context_val(ctx));
caml_zmq_raise_if(result == -1, "zmq_ctx_term");
CAML_ZMQ_Context_val(ctx) = NULL;
CAMLreturn (Val_unit);
}
/**
* Set context option
*/
static int const native_ctx_int_option_for[] = {
ZMQ_IO_THREADS,
ZMQ_MAX_SOCKETS,
ZMQ_IPV6
};
CAMLprim value caml_zmq_ctx_set_int_option(value socket, value option_name, value option_value) {
CAMLparam3 (socket, option_name, option_value);
int result = zmq_ctx_set(CAML_ZMQ_Context_val(socket),
native_ctx_int_option_for[Int_val(option_name)],
Int_val(option_value));
caml_zmq_raise_if(result == -1, "zmq_ctx_set");
CAMLreturn (Val_unit);
}
/**
* Get context option
*/
CAMLprim value caml_zmq_ctx_get_int_option(value socket, value option_name) {
CAMLparam2 (socket, option_name);
int result = zmq_ctx_get(CAML_ZMQ_Context_val(socket),
native_ctx_int_option_for[Int_val(option_name)]);
caml_zmq_raise_if(result == -1, "zmq_ctx_get");
CAMLreturn (Val_int(result));
}
/**
* Socket
*/
/* Order must match OCaml's kind declaration */
static int const socket_type_for_kind[] = {
ZMQ_PAIR,
ZMQ_PUB,
ZMQ_SUB,
ZMQ_REQ,
ZMQ_REP,
ZMQ_DEALER,
ZMQ_ROUTER,
ZMQ_PULL,
ZMQ_PUSH,
ZMQ_XPUB,
ZMQ_XSUB
};
CAMLprim value caml_zmq_socket(value ctx, value socket_kind) {
CAMLparam2 (ctx, socket_kind);
CAMLlocal1 (sock_value);
void *socket;
socket = zmq_socket(CAML_ZMQ_Context_val(ctx), socket_type_for_kind[Int_val(socket_kind)]);
caml_zmq_raise_if(socket == NULL, "zmq_socket");
sock_value = caml_zmq_copy_socket(socket);
CAMLreturn (sock_value);
}
/**
* Close
*/
CAMLprim value caml_zmq_close(value socket) {
CAMLparam1 (socket);
int result = zmq_close(CAML_ZMQ_Socket_val(socket));
caml_zmq_raise_if(result == -1, "zmq_close");
CAML_ZMQ_Socket_val(socket) = NULL;
CAMLreturn (Val_unit);
}
/**
* Set socket options
*/
static int const native_uint64_option_for[] = {
ZMQ_AFFINITY
};
CAMLprim value caml_zmq_set_uint64_option(value socket, value option_name, value socket_option) {
CAMLparam3 (socket, option_name, socket_option);
uint64_t val = Uint64_val(socket_option);
int result = zmq_setsockopt(CAML_ZMQ_Socket_val(socket),
native_uint64_option_for[Int_val(option_name)],
&val,
sizeof(val));
caml_zmq_raise_if(result == -1, "zmq_setsockopt");
CAMLreturn (Val_unit);
}
static int const native_int64_option_for[] = {
ZMQ_MAXMSGSIZE
};
CAMLprim value caml_zmq_set_int64_option(value socket, value option_name, value socket_option) {
CAMLparam3 (socket, option_name, socket_option);
int64_t val = Int64_val(socket_option);
int result = zmq_setsockopt(CAML_ZMQ_Socket_val(socket),
native_int64_option_for[Int_val(option_name)],
&val,
sizeof(val));
caml_zmq_raise_if(result == -1, "zmq_setsockopt");
CAMLreturn (Val_unit);
}
static int const native_bytes_option_for[] = {
ZMQ_IDENTITY,
ZMQ_SUBSCRIBE,
ZMQ_UNSUBSCRIBE,
ZMQ_LAST_ENDPOINT,
ZMQ_TCP_ACCEPT_FILTER,
ZMQ_PLAIN_USERNAME,
ZMQ_PLAIN_PASSWORD,
ZMQ_CURVE_PUBLICKEY,
ZMQ_CURVE_SECRETKEY,
ZMQ_CURVE_SERVERKEY,
ZMQ_ZAP_DOMAIN,
};
int caml_zmq_set_string_option(value socket, value option_name, value socket_option) {
CAMLparam3 (socket, option_name, socket_option);
char *option_value = String_val(socket_option);
size_t option_size = caml_string_length(socket_option);
int result = zmq_setsockopt(CAML_ZMQ_Socket_val(socket),
native_bytes_option_for[Int_val(option_name)],
option_value,
option_size);
caml_zmq_raise_if(result == -1, "zmq_setsockopt");
CAMLreturn (Val_unit);
}
static int const native_int_option_for[] = {
ZMQ_RATE,
ZMQ_RECOVERY_IVL,
ZMQ_SNDBUF,
ZMQ_RCVBUF,
ZMQ_RCVMORE,
ZMQ_EVENTS,
ZMQ_TYPE,
ZMQ_LINGER,
ZMQ_RECONNECT_IVL,
ZMQ_BACKLOG,
ZMQ_RECONNECT_IVL_MAX,
ZMQ_SNDHWM,
ZMQ_RCVHWM,
ZMQ_MULTICAST_HOPS,
ZMQ_RCVTIMEO,
ZMQ_SNDTIMEO,
ZMQ_IPV6,
ZMQ_ROUTER_MANDATORY,
ZMQ_TCP_KEEPALIVE,
ZMQ_TCP_KEEPALIVE_CNT,
ZMQ_TCP_KEEPALIVE_IDLE,
ZMQ_TCP_KEEPALIVE_INTVL,
ZMQ_IMMEDIATE,
ZMQ_XPUB_VERBOSE,
ZMQ_MECHANISM,
ZMQ_PLAIN_SERVER,
ZMQ_CURVE_SERVER,
ZMQ_PROBE_ROUTER,
ZMQ_REQ_CORRELATE,
ZMQ_REQ_RELAXED,
ZMQ_CONFLATE,
};
CAMLprim value caml_zmq_set_int_option(value socket, value option_name, value socket_option) {
CAMLparam3 (socket, option_name, socket_option);
int val = Int_val(socket_option);
int result = zmq_setsockopt(CAML_ZMQ_Socket_val(socket),
native_int_option_for[Int_val(option_name)],
&val,
sizeof(val));
caml_zmq_raise_if(result == -1, "zmq_setsockopt");
CAMLreturn (Val_unit);
}
/**
* Get socket options
*/
CAMLprim value caml_zmq_get_uint64_option(value socket, value option_name) {
CAMLparam2 (socket, option_name);
uint64_t mark;
size_t mark_size = sizeof (mark);
int result = zmq_getsockopt (CAML_ZMQ_Socket_val(socket),
native_uint64_option_for[Int_val(option_name)],
&mark,
&mark_size);
caml_zmq_raise_if(result == -1, "zmq_getsockopt");
CAMLreturn (copy_uint64(mark));
}
CAMLprim value caml_zmq_get_int64_option(value socket, value option_name) {
CAMLparam2 (socket, option_name);
int64_t mark;
size_t mark_size = sizeof (mark);
int result = zmq_getsockopt (CAML_ZMQ_Socket_val(socket),
native_int64_option_for[Int_val(option_name)],
&mark,
&mark_size);
caml_zmq_raise_if(result == -1, "zmq_getsockopt");
CAMLreturn (caml_copy_int64(mark));
}
CAMLprim value caml_zmq_get_string_option(value socket, value option_name, value option_maxlen) {
CAMLparam3 (socket, option_name, option_maxlen);
char buffer[256];
size_t buffer_size = Unsigned_long_val(option_maxlen);
assert(buffer_size < sizeof (buffer));
int result = zmq_getsockopt (CAML_ZMQ_Socket_val(socket),
native_bytes_option_for[Int_val(option_name)],
buffer,
&buffer_size);
caml_zmq_raise_if(result == -1, "zmq_getsockopt");
buffer[buffer_size] = '\0';
CAMLreturn (caml_copy_string(buffer));
}
CAMLprim value caml_zmq_get_int_option(value socket, value option_name) {
CAMLparam2 (socket, option_name);
int mark;
size_t mark_size = sizeof (mark);
int result = zmq_getsockopt (CAML_ZMQ_Socket_val(socket),
native_int_option_for[Int_val(option_name)],
&mark,
&mark_size);
caml_zmq_raise_if(result == -1, "zmq_getsockopt");
CAMLreturn (Val_int(mark));
}
CAMLprim value caml_zmq_get_events(value socket) {
CAMLparam1 (socket);
uint32_t event = 0;
size_t event_size = sizeof (event);
int result = zmq_getsockopt (CAML_ZMQ_Socket_val(socket),
ZMQ_EVENTS,
&event,
&event_size);
caml_zmq_raise_if(result == -1, "zmq_getsockopt");
int event_type = 0; /* No_event */
if (event & ZMQ_POLLIN) {
event_type = 1; /* Poll_in */
if (event & ZMQ_POLLOUT) {
event_type = 3; /* Poll_in_out */
}
} else if (event & ZMQ_POLLOUT) {
event_type = 2; /* Poll_out */
} else if (event & ZMQ_POLLERR) {
event_type = 4; /* Poll_error */
}
CAMLreturn (Val_int(event_type));
}
CAMLprim value caml_zmq_get_fd(value socket) {
CAMLparam1 (socket);
fd_type fd;
size_t mark_size = sizeof (fd);
int result = zmq_getsockopt (CAML_ZMQ_Socket_val(socket),
ZMQ_FD,
(void *)&fd,
&mark_size);
caml_zmq_raise_if(result == -1, "zmq_getsockopt");
CAMLreturn (Val_fd(fd));
}
/**
* Connect
*/
CAMLprim value caml_zmq_connect(value socket, value string_address) {
CAMLparam2 (socket, string_address);
int result = zmq_connect(CAML_ZMQ_Socket_val(socket), String_val(string_address));
caml_zmq_raise_if(result == -1, "zmq_connect");
CAMLreturn(Val_unit);
}
/**
* Disconnect
*/
CAMLprim value caml_zmq_disconnect(value socket, value string_address) {
CAMLparam2 (socket, string_address);
int result = zmq_disconnect(CAML_ZMQ_Socket_val(socket), String_val(string_address));
caml_zmq_raise_if(result == -1, "zmq_disconnect");
CAMLreturn(Val_unit);
}
/**
* Bind
*/
CAMLprim value caml_zmq_bind(value socket, value string_address) {
CAMLparam2 (socket, string_address);
int result = zmq_bind(CAML_ZMQ_Socket_val(socket), String_val(string_address));
caml_zmq_raise_if(result == -1, "zmq_bind");
CAMLreturn(Val_unit);
}
/**
* Unbind
*/
CAMLprim value caml_zmq_unbind(value socket, value string_address) {
CAMLparam2 (socket, string_address);
int result = zmq_unbind(CAML_ZMQ_Socket_val(socket), String_val(string_address));
caml_zmq_raise_if(result == -1, "zmq_unbind");
CAMLreturn(Val_unit);
}
/**
* Send
*/
CAMLprim value caml_zmq_send(value socket, value string, value block_flag, value more_flag) {
CAMLparam4 (socket, string, block_flag, more_flag);
int option = 0;
if (! Bool_val(block_flag)) option |= ZMQ_NOBLOCK;
if (Bool_val(more_flag)) option |= ZMQ_SNDMORE;
void *sock = CAML_ZMQ_Socket_val(socket);
zmq_msg_t msg;
int length = caml_string_length(string);
int result = zmq_msg_init_size(&msg, length);
caml_zmq_raise_if(result == -1, "zmq_msg_init_size");
/* Doesn't copy '\0' */
memcpy ((void *) zmq_msg_data (&msg), String_val(string), length);
caml_release_runtime_system();
result = zmq_msg_send(&msg, sock, option);
caml_acquire_runtime_system();
int errno;
if (result == -1) {
errno = zmq_errno();
zmq_msg_close (&msg);
caml_zmq_raise(errno, zmq_strerror(errno), "zmq_msg_send");
}
int close_result = zmq_msg_close (&msg);
caml_zmq_raise_if(close_result == -1, "zmq_msg_close");
CAMLreturn(Val_unit);
}
/**
* Receive
*/
CAMLprim value caml_zmq_recv(value socket, value block_flag) {
CAMLparam2 (socket, block_flag);
CAMLlocal1 (message);
int option = 0;
if (!Bool_val(block_flag)) option |= ZMQ_NOBLOCK;
void *sock = CAML_ZMQ_Socket_val(socket);
zmq_msg_t msg;
int result = zmq_msg_init (&msg);
caml_zmq_raise_if(result == -1, "zmq_msg_init");
caml_release_runtime_system();
result = zmq_msg_recv(&msg, sock, option);
caml_acquire_runtime_system();
int errno;
if (result == -1) {
errno = zmq_errno();
zmq_msg_close (&msg);
caml_zmq_raise(errno, zmq_strerror(errno), "zmq_msg_recv");
}
size_t size = zmq_msg_size (&msg);
message = caml_alloc_string(size);
memcpy (String_val(message), zmq_msg_data (&msg), size);
result = zmq_msg_close(&msg);
caml_zmq_raise_if(result == -1, "zmq_msg_close");
CAMLreturn (message);
}
/**
* msg values
*/
void caml_zmq_remove_generational_global_root(void *data __attribute__((unused)), void *hint) {
CAMLparam0();
caml_remove_generational_global_root(hint);
CAMLreturn0;
}
/**
* Send msg
*/
CAMLprim value caml_zmq_send_msg(value socket, value msg, value block_flag, value more_flag) {
CAMLparam4 (socket, msg, block_flag, more_flag);
int option = 0;
if (! Bool_val(block_flag)) option |= ZMQ_NOBLOCK;
if (Bool_val(more_flag)) option |= ZMQ_SNDMORE;
void *sock = CAML_ZMQ_Socket_val(socket);
zmq_msg_t *cmsg;
cmsg = (zmq_msg_t *)CAML_ZMQ_Msg_val(msg);
caml_release_runtime_system();
int result = zmq_msg_send(cmsg, sock, option);
caml_acquire_runtime_system();
int errno;
if (result == -1) {
errno = zmq_errno();
caml_zmq_raise(errno, zmq_strerror(errno), "zmq_msg_send");
}
CAMLreturn(Val_unit);
}
/**
* Receive msg
*/
CAMLprim value caml_zmq_recv_msg(value socket, value block_flag) {
CAMLparam2(socket, block_flag);
int option = 0;
if (!Bool_val(block_flag)) option |= ZMQ_NOBLOCK;
void *sock = CAML_ZMQ_Socket_val(socket);
zmq_msg_t *msg;
msg = (zmq_msg_t *)malloc(sizeof(zmq_msg_t));
int result = zmq_msg_init (msg);
int errno;
if (result == -1) {
errno = zmq_errno();
free(msg);
caml_zmq_raise(errno, zmq_strerror(errno), "zmq_msg_init");
}
caml_release_runtime_system();
result = zmq_msg_recv(msg, sock, option);
caml_acquire_runtime_system();
if (result == -1) {
errno = zmq_errno();
zmq_msg_close (msg);
free(msg);
caml_zmq_raise(errno, zmq_strerror(errno), "zmq_msg_recv");
}
CAMLreturn (caml_zmq_copy_msg(msg));
}
/**
* Msg values
*/
CAMLprim value caml_zmq_msg_init_data(value ba, value offset, value len) {
CAMLparam3(ba, offset, len);
CAMLlocal1(msg);
zmq_msg_t *cmsg;
cmsg = (zmq_msg_t *)malloc(sizeof(zmq_msg_t));
caml_register_generational_global_root(&ba);
int result = zmq_msg_init_data(cmsg, (char*)Caml_ba_data_val(ba) + Int_val(offset), Int_val(len), (void *)caml_zmq_remove_generational_global_root, (void *)ba);
int errno;
if (result == -1) {
errno = zmq_errno();
zmq_msg_close(cmsg);
free(cmsg);
caml_zmq_raise(errno, zmq_strerror(errno), "zmq_msg_init_data");
}
CAMLreturn(caml_zmq_copy_msg(cmsg));
}
CAMLprim value caml_zmq_msg_size(value msg) {
CAMLparam1(msg);
CAMLreturn(Val_int(zmq_msg_size(CAML_ZMQ_Msg_val(msg))));
}
CAMLprim value caml_zmq_msg_data(value msg) {
CAMLparam1(msg);
CAMLlocal1(data);
data = caml_ba_alloc_dims(CAML_BA_UINT8 | CAML_BA_C_LAYOUT | CAML_BA_EXTERNAL,
1,
zmq_msg_data(CAML_ZMQ_Msg_val(msg)),
zmq_msg_size(CAML_ZMQ_Msg_val(msg)));
CAMLreturn(data);
}
CAMLprim value caml_zmq_msg_close(value msg) {
CAMLparam1(msg);
zmq_msg_close(CAML_ZMQ_Msg_val(msg));
CAMLreturn(Val_unit);
}
CAMLprim value caml_zmq_msg_gets(value msg, value property) {
CAMLparam2(msg, property);
CAMLlocal1(result);
const char *r = zmq_msg_gets(CAML_ZMQ_Msg_val(msg), String_val(property));
caml_zmq_raise_if(!r, "zmq_msg_gets");
result = caml_copy_string(r);
CAMLreturn(result);
}
/**
* Devices
*/
CAMLprim value caml_zmq_proxy2(value frontend, value backend) {
CAMLparam2 (frontend, backend);
void *native_frontend = CAML_ZMQ_Socket_val(frontend);
void *native_backend = CAML_ZMQ_Socket_val(backend);
caml_release_runtime_system();
int result = zmq_proxy(native_frontend, native_backend, NULL);
caml_acquire_runtime_system();
caml_zmq_raise_if(result == -1, "zmq_proxy");
CAMLreturn (Val_unit);
}
CAMLprim value caml_zmq_proxy3(value frontend, value backend, value capture) {
CAMLparam3 (frontend, backend, capture);
void *native_frontend = CAML_ZMQ_Socket_val(frontend);
void *native_backend = CAML_ZMQ_Socket_val(backend);
void *native_capture = CAML_ZMQ_Socket_val(capture);
caml_release_runtime_system();
int result = zmq_proxy(native_frontend, native_backend, native_capture);
caml_acquire_runtime_system();
caml_zmq_raise_if(result == -1, "zmq_proxy");
CAMLreturn (Val_unit);
}
CAMLprim value caml_zmq_socket_monitor(value socket, value address) {
CAMLparam2 (socket, address);
caml_release_runtime_system();
int result = zmq_socket_monitor(CAML_ZMQ_Socket_val(socket), String_val(address), ZMQ_EVENT_ALL);
caml_acquire_runtime_system();
caml_zmq_raise_if(result == -1, "zmq_socket_monitor");
CAMLreturn (Val_unit);
}
enum event_type {
CONNECTED = 0,
CONNECT_DELAYED,
CONNECT_RETRIED,
LISTENING,
BIND_FAILED,
ACCEPTED,
ACCEPT_FAILED,
CLOSED,
CLOSE_FAILED,
DISCONNECTED,
MONITOR_STOPPED,
HANDSHAKE_FAILED_NO_DETAIL,
HANDSHAKE_SUCCEEDED,
HANDSHAKE_FAILED_PROTOCOL,
HANDSHAKE_FAILED_AUTH
};
/** Decode monitor event */
CAMLprim value caml_decode_monitor_event(value event_val, value addr) {
CAMLparam2 (event_val, addr);
CAMLlocal1 (result);
const char *data = String_val(event_val);
const uint16_t *event = (const uint16_t *)data;
const int32_t *param = (const int32_t *)(data + 2);
switch (*event) {
case ZMQ_EVENT_CONNECTED:
result = caml_alloc(2, CONNECTED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_fd(*param));
break;
case ZMQ_EVENT_CONNECT_DELAYED:
result = caml_alloc(1, CONNECT_DELAYED);
Store_field(result, 0, addr);
break;
case ZMQ_EVENT_CONNECT_RETRIED:
result = caml_alloc(2, CONNECT_RETRIED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_int(*param));
break;
case ZMQ_EVENT_LISTENING:
result = caml_alloc(2, LISTENING);
Store_field(result, 0, addr);
Store_field(result, 1, Val_fd(*param));
break;
case ZMQ_EVENT_BIND_FAILED:
result = caml_alloc(3, BIND_FAILED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_int(*param));
Store_field(result, 2, caml_copy_string(zmq_strerror(*param)));
break;
case ZMQ_EVENT_ACCEPTED:
result = caml_alloc(2, ACCEPTED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_fd(*param));
break;
case ZMQ_EVENT_ACCEPT_FAILED:
result = caml_alloc(3, ACCEPT_FAILED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_int(*param));
Store_field(result, 2, caml_copy_string(zmq_strerror(*param)));
break;
case ZMQ_EVENT_CLOSED:
result = caml_alloc(2, CLOSED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_fd(*param));
break;
case ZMQ_EVENT_CLOSE_FAILED:
result = caml_alloc(3, CLOSE_FAILED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_int(*param));
Store_field(result, 2, caml_copy_string(zmq_strerror(*param)));
break;
case ZMQ_EVENT_DISCONNECTED:
result = caml_alloc(2, DISCONNECTED);
Store_field(result, 0, addr);
Store_field(result, 1, Val_fd(*param));
break;
#if ZMQ_VERSION_MINOR >= 3
case ZMQ_EVENT_MONITOR_STOPPED:
result = caml_alloc(1, MONITOR_STOPPED);
Store_field(result, 0, addr);
break;
case ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL:
result = caml_alloc(1, HANDSHAKE_FAILED_NO_DETAIL);
Store_field(result, 0, addr);
break;
case ZMQ_EVENT_HANDSHAKE_SUCCEEDED:
result = caml_alloc(1, HANDSHAKE_SUCCEEDED);
Store_field(result, 0, addr);
break;
case ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL:
result = caml_alloc(2, HANDSHAKE_FAILED_PROTOCOL);
Store_field(result, 0, addr);
Store_field(result, 1, Val_fd(*param));
break;
case ZMQ_EVENT_HANDSHAKE_FAILED_AUTH:
result = caml_alloc(2, HANDSHAKE_FAILED_AUTH);
Store_field(result, 0, addr);
Store_field(result, 1, Val_fd(*param));
break;
#endif
default:
caml_invalid_argument("Unknown event type");
break;
}
CAMLreturn(result);
}
/**
* Z85
*/
CAMLprim value caml_z85_encode(value source) {
CAMLparam1 (source);
CAMLlocal1 (result);
/*
* zmq_z85_encode writes a null terminator. However, OCaml does not
* need a null terminator. The code below does not allocate space for
* a null terminator, but zmq_z85_encode will not encounter an overrun,
* as OCaml string representation guarantees that one byte past the
* end of string is allocated and contains '\0'.
*
* See http://caml.inria.fr/pub/docs/oreilly-book/html/book-ora115.html#@concepts266
* for details.
*/
int length = caml_string_length(source);
result = caml_alloc_string(length / 4 * 5);
if (zmq_z85_encode(String_val(result), (uint8_t*) String_val(source), length) == NULL)
caml_invalid_argument("zmq_z85_encode");
CAMLreturn(result);
}
CAMLprim value caml_z85_decode(value source) {
CAMLparam1 (source);
CAMLlocal1 (result);
result = caml_alloc_string(caml_string_length(source) * 4 / 5);
if (zmq_z85_decode((uint8_t*) String_val(result), String_val(source)) == NULL)
caml_invalid_argument("zmq_z85_decode");
CAMLreturn(result);
}
/**
* Key generation
*/
CAMLprim value caml_curve_keypair(value unit) {
CAMLparam1 (unit);
CAMLlocal3 (public, secret, tuple);
/* See the notice in caml_z85_encode. */
public = caml_alloc_string(40);
secret = caml_alloc_string(40);
int result = zmq_curve_keypair(String_val(public), String_val(secret));
caml_zmq_raise_if(result == -1, "zmq_curve_keypair");
tuple = caml_alloc_tuple(2);
Store_field(tuple, 0, public);
Store_field(tuple, 1, secret);
CAMLreturn (tuple);
}
|
roddyyaga/ocaml-zmq
|
zmq/src/fail.h
|
<gh_stars>10-100
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#ifndef CAML_ZMQ_FAIL_H_
#define CAML_ZMQ_FAIL_H_
void caml_zmq_raise(int err_no, const char *err_str, const char *name);
void caml_zmq_raise_if(int condition, const char *name);
#endif /* CAML_ZMQ_FAIL_H_ */
|
roddyyaga/ocaml-zmq
|
zmq/src/poll.c
|
<gh_stars>10-100
#include "poll.h"
#include <caml/memory.h>
#include <caml/custom.h>
#include <caml/threads.h>
#include <caml/fail.h>
#include <caml/alloc.h>
#include <caml/unixsupport.h>
#include "fail.h"
#include "socket.h"
#include <stdio.h>
static void custom_finalize_poll(value poll) {
free(CAML_ZMQ_Poll_val(poll)->poll_items);
}
static struct custom_operations caml_zmq_poll_ops = {
"org.zeromq.poll",
custom_finalize_poll,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default
#ifdef custom_compare_ext_default
, custom_compare_ext_default
#endif
#ifdef custom_fixed_length_default
, custom_fixed_length_default
#endif
};
CAMLprim value caml_zmq_poll_of_pollitem_array(value pollitem_array) {
CAMLparam1 (pollitem_array);
CAMLlocal2 (poll, current_elem);
int n = Wosize_val(pollitem_array);
zmq_pollitem_t *items = malloc(sizeof(zmq_pollitem_t) * n);
if (items == NULL) {
unix_error(ENOMEM, "malloc", Nothing);
}
int i;
for(i = 0; i < n; i++) {
current_elem = Field(pollitem_array, i);
items[i].socket = CAML_ZMQ_Socket_val(Field(current_elem, 0));
items[i].events = CAML_ZMQ_Mask_val(Field(current_elem, 1));
}
poll= caml_alloc_custom(&caml_zmq_poll_ops,
sizeof(struct caml_zmq_poll),
0, 1);
CAML_ZMQ_Poll_val(poll)->num_elems = n;
CAML_ZMQ_Poll_val(poll)->poll_items = items;
CAMLreturn (poll);
}
/* Sync with variant declaration */
enum caml_zmq_event_mask {
In = 0,
Out,
In_out
};
value CAML_ZMQ_Val_mask(short mask) {
if(mask & ZMQ_POLLIN) {
if(mask & ZMQ_POLLOUT) {
return Val_int(In_out);
}
return Val_int(In);
}
if(mask & ZMQ_POLLOUT) {
return Val_int(Out);
}
abort(); /* unreachable */
}
short CAML_ZMQ_Mask_val (value mask) {
switch(Int_val(mask)) {
case In: return ZMQ_POLLIN;
case Out: return ZMQ_POLLOUT;
case In_out: return ZMQ_POLLOUT | ZMQ_POLLIN;
}
abort(); /* unreachable */
}
CAMLprim value caml_zmq_poll(value poll, value timeout) {
CAMLparam2 (poll, timeout);
CAMLlocal2 (events, some);
int n = CAML_ZMQ_Poll_val(poll)->num_elems;
zmq_pollitem_t *items = CAML_ZMQ_Poll_val(poll)->poll_items;
int tm = Int_val(timeout);
caml_release_runtime_system();
int num_event_sockets = zmq_poll(items, n, tm);
caml_acquire_runtime_system();
caml_zmq_raise_if(num_event_sockets == -1, "zmq_poll");
events = caml_alloc(n, 0);
int i;
for(i = 0; i < n; i++) {
if (!((items[i].revents & ZMQ_POLLIN) || (items[i].revents & ZMQ_POLLOUT))) {
Store_field(events, i, Val_int(0)); /* None */
} else {
some = caml_alloc(1, 0);
Store_field(some, 0, CAML_ZMQ_Val_mask(items[i].revents));
Store_field(events, i, some);
}
}
CAMLreturn (events);
}
|
roddyyaga/ocaml-zmq
|
zmq/src/socket.h
|
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#ifndef CAML_ZMQ_SOCKET_H_
#define CAML_ZMQ_SOCKET_H_
#include <caml/mlvalues.h>
#define CAML_ZMQ_Socket_val(v) (*((void **) Data_custom_val(v)))
value caml_zmq_copy_socket(void *zmq_socket);
#endif /* CAML_ZMQ_SOCKET_H_ */
|
roddyyaga/ocaml-zmq
|
zmq/src/context.c
|
<gh_stars>10-100
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#include "context.h"
#include <caml/custom.h>
#include <caml/memory.h>
#include <zmq.h>
static void custom_finalize_context(value context) {
if (CAML_ZMQ_Context_val(context)) {
fprintf(stderr, "Error: Context not closed before finalization\n");
}
}
static struct custom_operations caml_zmq_context_ops = {
"org.zeromq.context",
custom_finalize_context,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default
#ifdef custom_compare_ext_default
, custom_compare_ext_default
#endif
#ifdef custom_fixed_length_default
, custom_fixed_length_default
#endif
};
value caml_zmq_copy_context(void *zmq_context) {
CAMLparam0 ();
CAMLlocal1 (context);
context = caml_alloc_custom(&caml_zmq_context_ops, sizeof (zmq_context), 0, 1);
CAML_ZMQ_Context_val(context) = zmq_context;
CAMLreturn (context);
}
|
roddyyaga/ocaml-zmq
|
zmq/src/context.h
|
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#ifndef CAML_ZMQ_CONTEXT_H_
#define CAML_ZMQ_CONTEXT_H_
#include <caml/mlvalues.h>
#define CAML_ZMQ_Context_val(v) (*((void **) Data_custom_val(v)))
value caml_zmq_copy_context(void *zmq_context);
#endif /* CAML_ZMQ_CONTEXT_H_ */
|
roddyyaga/ocaml-zmq
|
zmq/src/fail.c
|
/*
* Copyright (c) 2011 <NAME> and contributors
*/
#include "fail.h"
#include <zmq.h>
#include <caml/callback.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/memory.h>
#include <caml/unixsupport.h>
/* This table must be synchronized with Zmq.internal_error. */
static int const caml_zmq_error_table[] = {
ENOTSUP,
EPROTONOSUPPORT,
ENOBUFS,
ENETDOWN,
EADDRINUSE,
EADDRNOTAVAIL,
ECONNREFUSED,
EINPROGRESS,
ENOTSOCK,
EMSGSIZE,
EAFNOSUPPORT,
ENETUNREACH,
ECONNABORTED,
ECONNRESET,
ENOTCONN,
ETIMEDOUT,
EHOSTUNREACH,
ENETRESET,
EFSM,
ENOCOMPATPROTO,
ETERM,
EMTHREAD,
};
/* This must be the last value of the variant. */
static int const caml_zmq_EUNKNOWN =
(sizeof caml_zmq_error_table) / (sizeof caml_zmq_error_table[0]);
void caml_zmq_raise(int err_no, const char *err_str, const char *name) {
CAMLparam0 ();
/* err_no can be a standard Unix error code, or it can be a ZMQ-defined
* error code in the range above ZMQ_HAUSNUMERO. If the system headers are
* missing certain Unix codes, they get redefined in zmq.h with a number
* above ZMQ_HAUSNUMERO. That range also contains new ZMQ-specific error
* codes.
*/
if (err_no < ZMQ_HAUSNUMERO) {
unix_error(err_no, (char *) name, Nothing);
} else {
int error_to_raise = caml_zmq_EUNKNOWN;
int i;
for (i = 0; i < caml_zmq_EUNKNOWN; i++) {
if (err_no == caml_zmq_error_table[i]) {
error_to_raise = i;
break;
}
}
/* From http://caml.inria.fr/pub/docs/manual-ocaml-4.01/intfc.html#sec439:
If the function f does not return, but raises an exception that
escapes the scope of the application, then this exception is
propagated to the next enclosing OCaml code, skipping over the C
code. That is, if an OCaml function f calls a C function g that calls
back an OCaml function h that raises a stray exception, then the
execution of g is interrupted and the exception is propagated back
into f.
*/
caml_callback3(*caml_named_value("Zmq.zmq_raise"),
Val_int(error_to_raise),
caml_copy_string(err_str),
caml_copy_string(name)
);
}
CAMLreturn0;
}
void caml_zmq_raise_if(int condition, const char *location) {
if (condition) {
int err_no = zmq_errno();
const char *err_str = zmq_strerror(err_no);
caml_zmq_raise(err_no, err_str, location);
}
}
|
pniekamp/datum-studio
|
src/common/qcdoubleslider.h
|
<gh_stars>1-10
//
// QcDoubleSlider
//
#pragma once
#include <QSlider>
//---------------- QcDoubleSlider ----------------------
//------------------------------------------------------
class QcDoubleSlider : public QSlider
{
Q_OBJECT
public:
QcDoubleSlider(QWidget *parent = 0);
QcDoubleSlider(Qt::Orientation orientation, QWidget *parent = 0);
double value() const;
void setDecimals(int decimals);
void setRange(int min, int max);
void setRange(double min, double max);
void setMinimum(int min);
void setMinimum(double min);
void setMaximum(int max);
void setMaximum(double max);
public slots:
void setValue(int value);
void setValue(double value);
void updateValue(double value);
signals:
void valueChanged(double value);
void valueUpdated(double value);
protected:
void sliderChange(SliderChange change);
private:
double m_min;
double m_max;
int m_decimals;
};
|
pniekamp/datum-studio
|
src/plugins/edit/editorapi.h
|
<filename>src/plugins/edit/editorapi.h<gh_stars>1-10
//
// Editor API
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "api.h"
#if defined(EDITPLUGIN)
# define EDITPLUGIN_EXPORT Q_DECL_EXPORT
#else
# define EDITPLUGIN_EXPORT Q_DECL_IMPORT
#endif
namespace Studio
{
//-------------------------- EditorManager ----------------------------------
//---------------------------------------------------------------------------
class EDITPLUGIN_EXPORT EditorManager : public QObject
{
Q_OBJECT
public:
virtual void open_editor(QString const &type, QString const &path) = 0;
virtual int save_all() = 0;
virtual int close_all() = 0;
protected:
virtual ~EditorManager() { }
};
}
|
pniekamp/datum-studio
|
src/plugins/animation/animationview.h
|
//
// Animation View
//
//
// Copyright (C) 2017 <NAME>
//
#pragma once
#include "animation.h"
#include "viewport.h"
//-------------------------- AnimationView ----------------------------------
//---------------------------------------------------------------------------
class AnimationView : public Viewport
{
Q_OBJECT
public:
AnimationView(QWidget *parent = nullptr);
public slots:
void view(Studio::Document *document);
protected slots:
void refresh();
protected:
void invalidate();
void keyPressEvent(QKeyEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);
void timerEvent(QTimerEvent *event);
void paintEvent(QPaintEvent *event);
private:
int m_timerid;
float m_yawsign;
lml::Vec3 m_focuspoint;
QPoint m_mousepresspos, m_mousemovepos;
float m_time;
float m_duration;
std::vector<lml::Transform> m_bones;
std::vector<AnimationDocument::Joint> m_joints;
AnimationDocument m_document;
};
|
pniekamp/datum-studio
|
src/plugins/sprite/spriteproperties.h
|
//
// Sprite Properties
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "spritesheet.h"
#include "ui_spriteproperties.h"
#include <QDockWidget>
//-------------------------- SpriteProperties -------------------------------
//---------------------------------------------------------------------------
class SpriteProperties : public QDockWidget
{
Q_OBJECT
public:
SpriteProperties(QWidget *parent = nullptr);
public slots:
void edit(Studio::Document *document);
protected slots:
void refresh();
protected:
void on_sprite_build_complete(Studio::Document *document, QString const &path);
private:
Ui::Properties ui;
SpriteSheetDocument m_document;
};
|
pniekamp/datum-studio
|
src/common/qcdoublespinbox.h
|
//
// QcDoubleSpinBox
//
#pragma once
#include <QDoubleSpinBox>
//---------------- QcDoubleSpinBox ---------------------
//------------------------------------------------------
class QcDoubleSpinBox : public QDoubleSpinBox
{
Q_OBJECT
public:
QcDoubleSpinBox(QWidget *parent = 0);
double value() const { return m_value; }
public slots:
void updateValue(double value);
signals:
void valueChanged(double value);
void valueUpdated(double value);
protected:
void keyPressEvent(QKeyEvent *event);
void focusOutEvent(QFocusEvent *event);
void wheelEvent(QWheelEvent *event);
private:
bool m_editing;
double m_value;
};
|
pniekamp/datum-studio
|
include/projectapi.h
|
#include "../src/plugins/project/projectapi.h"
|
pniekamp/datum-studio
|
src/plugins/terrain/terrainmaterial.h
|
<gh_stars>1-10
//
// Terrain Material Build
//
//
// Copyright (C) 2017 <NAME>
//
#pragma once
#include "documentapi.h"
#include "datum/math.h"
#include "packapi.h"
#include <string>
//-------------------------- TerrainMaterialDocument ------------------------
//---------------------------------------------------------------------------
class TerrainMaterialDocument : public QObject
{
Q_OBJECT
public:
static void create(std::string const &path, lml::Color4 const &color);
static void hash(Studio::Document *document, size_t *key);
static void build_hash(Studio::Document *document, size_t *key);
static void build(Studio::Document *document, std::string const &path);
static void pack(Studio::PackerState &asset, std::ofstream &fout);
public:
TerrainMaterialDocument();
TerrainMaterialDocument(QString const &path);
TerrainMaterialDocument(Studio::Document *document);
TerrainMaterialDocument(TerrainMaterialDocument const &document);
TerrainMaterialDocument operator =(TerrainMaterialDocument const &document);
operator Studio::Document *() const { return m_document; }
Studio::Document *operator *() const { return m_document; }
Studio::Document *operator ->() const { return m_document; }
public:
lml::Color4 color() const { return lml::Color4(m_definition["color.r"].toDouble(), m_definition["color.g"].toDouble(), m_definition["color.b"].toDouble(), m_definition["color.a"].toDouble(1)); }
float metalness() const { return m_definition["metalness"].toDouble(0); }
float roughness() const { return m_definition["roughness"].toDouble(1); }
float reflectivity() const { return m_definition["reflectivity"].toDouble(0.5); }
float emissive() const { return m_definition["emissive"].toDouble(0); }
int layers() const { return m_materials.size(); }
Studio::Document *layer(int index) const { return m_materials[index]; }
public:
void set_color(lml::Color4 const &color);
void set_metalness(float metalness);
void set_roughness(float roughness);
void set_reflectivity(float reflectivity);
void set_emissive(float emissive);
void add_layer(int position, QString const &path);
void move_layer(int index, int position);
void erase_layer(int index);
signals:
void document_changed();
void dependant_changed();
private:
void attach(Studio::Document *document);
void touch(Studio::Document *document, QString const &path);
void refresh();
void update();
QJsonObject m_definition;
std::vector<unique_document> m_materials;
unique_document m_document;
};
|
pniekamp/datum-studio
|
src/plugins/build/buildmanager.h
|
//
// Build Management
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "api.h"
#include "buildapi.h"
#include <leap/threadcontrol.h>
#include <QDir>
#include <QUuid>
#include <QThreadPool>
class BuildManager;
//-------------------------- Builder ----------------------------------------
//---------------------------------------------------------------------------
class Builder : public QObject, public QRunnable
{
Q_OBJECT
public:
Builder(BuildManager *manager, Studio::Document *document);
void run();
signals:
void build_failure(Studio::Document *document);
void build_complete(Studio::Document *document, QString const &path);
private:
BuildManager *m_manager;
unique_document m_document;
};
//-------------------------- BuildManager -----------------------------------
//---------------------------------------------------------------------------
class BuildManager : public Studio::BuildManager
{
Q_OBJECT
public:
BuildManager();
QString basepath() const;
void request_build(Studio::Document *document, QObject *receiver, std::function<void (Studio::Document *, QString const &)> const ¬ify, std::function<void (Studio::Document *)> const &failure = nullptr);
void register_builder(QString const &type, QObject *builder);
public:
bool build(Studio::Document *document, QString *path);
protected:
void on_project_changed(QString const &projectfile);
void on_project_closing(bool *cancel);
void on_document_renamed(Studio::Document *document, QString const &src, QString const &dst);
private:
QDir m_path;
struct Build
{
QUuid id;
QString file;
size_t hash;
};
std::vector<Build> m_builds;
QUuid find_build(QString const &file, size_t key) const;
std::vector<Studio::Document*> m_pending;
QMap<QString, QObject*> m_builders;
mutable leap::threadlib::CriticalSection m_mutex;
};
|
pniekamp/datum-studio
|
src/plugins/skybox/skybox.h
|
//
// Skybox Build
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "documentapi.h"
#include "packapi.h"
#include <string>
//-------------------------- SkyboxDocument ---------------------------------
//---------------------------------------------------------------------------
class SkyboxDocument : public QObject
{
Q_OBJECT
public:
static void create(std::string const &path);
static void hash(Studio::Document *document, size_t *key);
static void build(Studio::Document *document, std::string const &path);
static void pack(Studio::PackerState &asset, std::ofstream &fout);
public:
SkyboxDocument();
SkyboxDocument(QString const &path);
SkyboxDocument(Studio::Document *document);
SkyboxDocument(SkyboxDocument const &document);
SkyboxDocument operator =(SkyboxDocument const &document);
operator Studio::Document *() const { return m_document; }
Studio::Document *operator *() const { return m_document; }
Studio::Document *operator ->() const { return m_document; }
public:
enum class Type
{
FaceImages,
SphericalMap
};
enum class Image
{
Front,
Left,
Right,
Back,
Top,
Bottom,
EnvMap
};
Type type() const { return static_cast<Type>(m_definition["type"].toInt()); }
int width() const { return m_definition["width"].toInt(); }
int height() const { return m_definition["height"].toInt(); }
Studio::Document *image(int image) const { return m_images[image]; }
Studio::Document *image(Image image) const { return m_images[static_cast<int>(image)]; }
public:
void set_type(Type type);
void set_width(int width);
void set_height(int height);
void set_image(Image image, QString const &path);
signals:
void document_changed();
void dependant_changed();
private:
void attach(Studio::Document *document);
void touch(Studio::Document *document, QString const &path);
void refresh();
void update();
QJsonObject m_definition;
std::vector<unique_document> m_images;
unique_document m_document;
};
|
pniekamp/datum-studio
|
src/plugins/animation/animationviewer.h
|
//
// Animation Viewer
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "documentapi.h"
#include "animationview.h"
#include "animationproperties.h"
#include <QMainWindow>
#include <QToolBar>
#include <QLabel>
#include <QSlider>
//-------------------------- AnimationViewer --------------------------------
//---------------------------------------------------------------------------
class AnimationViewer : public QMainWindow
{
Q_OBJECT
public:
AnimationViewer(QWidget *parent = nullptr);
virtual ~AnimationViewer();
public slots:
QToolBar *toolbar() const;
void view(Studio::Document *document);
void edit(Studio::Document *document);
private:
QToolBar *m_toolbar;
AnimationView *m_view;
AnimationProperties *m_properties;
};
|
pniekamp/datum-studio
|
src/plugins/skybox/skyboxeditor.h
|
<filename>src/plugins/skybox/skyboxeditor.h<gh_stars>1-10
//
// Skybox Editor
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "documentapi.h"
#include "skyboxview.h"
#include "skyboxproperties.h"
#include "qcslider.h"
#include "qcdoubleslider.h"
#include <QMainWindow>
#include <QToolBar>
//-------------------------- SkyboxEditor -----------------------------------
//---------------------------------------------------------------------------
class SkyboxEditor : public QMainWindow
{
Q_OBJECT
public:
SkyboxEditor(QWidget *parent = nullptr);
virtual ~SkyboxEditor();
public slots:
QToolBar *toolbar() const;
void view(Studio::Document *document);
void edit(Studio::Document *document);
private:
QToolBar *m_toolbar;
QcSlider *m_layerslider;
QcDoubleSlider *m_exposureslider;
SkyboxView *m_view;
SkyboxProperties *m_properties;
};
|
pniekamp/datum-studio
|
src/plugins/pack/packapi.h
|
//
// Pack API
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "api.h"
#include "documentapi.h"
#include <fstream>
#if defined(PACKPLUGIN)
# define PACKPLUGIN_EXPORT Q_DECL_EXPORT
#else
# define PACKPLUGIN_EXPORT Q_DECL_IMPORT
#endif
namespace Studio
{
struct PackerState
{
uint32_t id;
QString name;
QString type;
unique_document document;
uint32_t index;
std::string buildpath;
virtual uint32_t add_dependant(Studio::Document *document, QString type) = 0;
virtual uint32_t add_dependant(Studio::Document *document, uint32_t index, QString type) = 0;
};
//-------------------------- PackManager ------------------------------------
//---------------------------------------------------------------------------
class PACKPLUGIN_EXPORT PackManager : public QObject
{
Q_OBJECT
public:
virtual void register_packer(QString const &type, QObject *packer) = 0;
protected:
virtual ~PackManager() { }
};
}
|
pniekamp/datum-studio
|
src/platform.h
|
<reponame>pniekamp/datum-studio
//
// Datum Platform
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "api.h"
#include "datum.h"
#include "datum/renderer.h"
namespace Studio
{
class STUDIO_EXPORT Platform : public QObject
{
Q_OBJECT
public:
static const uint32_t RenderQueue = 0;
static const uint32_t TransferQueue = 1;
static DatumPlatform::PlatformInterface *instance();
public:
virtual AssetManager *assets() = 0;
virtual ResourceManager *resources() = 0;
virtual Vulkan::Surface create_surface(WId wid) = 0;
};
}
void initialise_platform(QWindow *window);
|
pniekamp/datum-studio
|
include/platform.h
|
#include "../src/platform.h"
|
pniekamp/datum-studio
|
src/plugins/font/fontview.h
|
//
// FontView
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "font.h"
#include <leap/concurrentqueue.h>
#include <QAbstractScrollArea>
//-------------------------- FontView ---------------------------------------
//---------------------------------------------------------------------------
class FontView : public QAbstractScrollArea
{
Q_OBJECT
public:
FontView(QWidget *parent = nullptr);
public slots:
void view(Studio::Document *document);
void set_zoom(float value);
signals:
void zoom_changed(float value);
protected slots:
void refresh();
void set_scale(float scale, QPoint const &focus);
protected:
void invalidate();
void on_font_build_complete(Studio::Document *document, QString const &path);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);
void resizeEvent(QResizeEvent *event);
void paintEvent(QPaintEvent *event);
private:
QPoint m_mousepresspos, m_mousemovepos;
float m_scale;
int m_border;
QImage m_image;
FontDocument m_document;
};
|
pniekamp/datum-studio
|
src/plugins/particle/particleproperties.h
|
//
// Particle Properties
//
//
// Copyright (C) 2017 <NAME>
//
#pragma once
#include "particlesystem.h"
#include "ui_particleproperties.h"
#include <QDockWidget>
//-------------------------- ParticleProperties -----------------------------
//---------------------------------------------------------------------------
class ParticleProperties : public QDockWidget
{
Q_OBJECT
public:
ParticleProperties(QWidget *parent = nullptr);
public slots:
void edit(Studio::Document *document);
void set_selection(int index);
signals:
void selection_changed(int index);
protected slots:
void refresh();
void on_MaxParticles_valueChanged(int value);
void on_SpriteSheet_itemDropped(QString const &path);
void on_Bound1_valueChanged(double value);
void on_Bound2_valueChanged(double value);
void on_Bound3_valueChanged(double value);
void on_Bound4_valueChanged(double value);
void on_Bound5_valueChanged(double value);
void on_Bound6_valueChanged(double value);
private:
Ui::Properties ui;
ParticleSystemDocument m_document;
};
|
pniekamp/datum-studio
|
src/common/viewport.h
|
<filename>src/common/viewport.h
//
// Datum Viewport
//
//
// Copyright (C) 2016 <NAME>
//
#pragma once
#include "datum.h"
#include "platform.h"
#include "documentapi.h"
#include <QWidget>
//-------------------------- Viewport ---------------------------------------
//---------------------------------------------------------------------------
class Viewport : public QWidget
{
Q_OBJECT
public:
Viewport(size_t slabsize = 8*1024, size_t storagesize = 2*1024*1024, QWidget *parent = nullptr);
virtual ~Viewport();
public:
class ResourceProxy
{
public:
ResourceProxy(ResourceManager *manager) : m_manager(manager) { }
template<typename Resource, typename ...Args>
unique_resource<Resource> create(Args... args) { return { m_manager, m_manager->create<Resource>(std::forward<Args>(args)...) }; }
template<typename Resource, typename ...Args>
void update(unique_resource<Resource> &resource, Args... args) { m_manager->update(resource, std::forward<Args>(args)...); }
template<typename Resource, typename ...Args>
unique_resource<Resource> load(size_t asset, Args... args);
template<typename Resource, typename ...Args>
unique_resource<Resource> load(std::istream &fin, size_t index, Args... args);
template<typename Resource, typename ...Args>
unique_resource<Resource> load(Studio::Document *document, size_t index, Args... args);
unique_resource<Mesh> make_plane(int sizex, int sizey, float scale = 1.0f, float tilex = 1.0f, float tiley = 1.0f);
public:
ResourceManager::TransferLump const *acquire_lump(size_t size) { return m_manager->acquire_lump(size); }
void release_lump(ResourceManager::TransferLump const *lump) { m_manager->release_lump(lump); }
private:
ResourceManager *m_manager;
};
ResourceProxy resources;
public:
Camera camera;
RenderParams renderparams;
bool prepare();
bool begin(SpriteList &apritelist, SpriteList::BuildState &buildstate);
void push_sprites(SpriteList const &apritelist);
bool begin(GeometryList &geometrylist, GeometryList::BuildState &buildstate);
void push_geometry(GeometryList const &geometrylist);
bool begin(ForwardList &forwardlist, ForwardList::BuildState &buildstate);
void push_forward(ForwardList const &forwardlist);
bool begin(OverlayList &overlaylist, OverlayList::BuildState &buildstate);
void push_overlays(OverlayList const &overlaylist);
void render();
protected:
void hideEvent(QHideEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
QPaintEngine *paintEngine() const override;
void paintEvent(QPaintEvent *event) override;
protected slots:
void resizedEvent();
private:
DatumPlatform::GameMemory pushbuffermemory;
PushBuffer m_pushbuffer;
RenderContext m_rendercontext;
Vulkan::Surface surface;
Vulkan::Swapchain swapchain;
Vulkan::Semaphore acquirecomplete;
Vulkan::Semaphore rendercomplete;
VkImage presentimages[2];
QTimer *m_resizetimer;
size_t m_resourcetoken;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.