strip out prosperon from cell
This commit is contained in:
@@ -1,218 +0,0 @@
|
||||
#include "3pfollow.h"
|
||||
#include <math.h>
|
||||
|
||||
// void ThirdPersonFollow::_ready() {
|
||||
// Target = dynamic_cast<Spatial*>(get_node(TargetPath));
|
||||
// ExternalFrame = dynamic_cast<Spatial*>(get_node(ExternalFramePath));
|
||||
// }
|
||||
|
||||
// void ThirdPersonFollow::_process(float delta_time) {
|
||||
|
||||
// if (Target != nullptr) {
|
||||
// // Get the frame of reference
|
||||
// if (has_node(ExternalFramePath) && get_node(ExternalFramePath) != this)
|
||||
// TFOR = dynamic_cast<Spatial*>(get_node(ExternalFramePath))->get_global_transform();
|
||||
// else
|
||||
// TFOR = Transform(Basis(glm::vec3::RIGHT(), glm::vec3::UP(), glm::vec3::FORWARD()), glm::vec3::ZERO());
|
||||
|
||||
// CalculateTargetOffset();
|
||||
// TargetPosition = CalculatePosition();
|
||||
|
||||
// translate(to_local(FrameBasedVectorLerp(get_global_translation(), TargetPosition, PositionSpeeds, delta_time)));
|
||||
|
||||
// set_rotation_degrees(get_rotation_degrees().linear_interpolate(RotationOffset, RotationSpeed * delta_time));
|
||||
// }
|
||||
|
||||
// // For rotation
|
||||
// // TODO: Add rotation offset in properly
|
||||
// //this->SetActorRotation(FMath::Lerp(this->GetActorRotation(), TargetRotation, RotationSpeed * DeltaTime));
|
||||
// //this->set_rotation(glm::quat(this->get_rotation().slerp(RotationOffset, RotationSpeed * DeltaTime)).get_euler());
|
||||
|
||||
// //set_global_rotation_degrees(get_global_rotation_degrees().linear_interpolate(RotationOffset, RotationSpeed * delta_time));
|
||||
|
||||
// // TODO: Figure out how to translate rotation to a global rotation
|
||||
// }
|
||||
|
||||
/*
|
||||
|
||||
glm::vec3 ThirdPersonFollow::CalculatePosition()
|
||||
{
|
||||
glm::vec3 p1 = CalculateCenter();
|
||||
|
||||
glm::vec3 p2 =
|
||||
XDirPosts ? GetPostsOffset(TFOR.Right(),
|
||||
FloatWidths.
|
||||
x) : GetExtentsOffset(TFOR.Right(),
|
||||
FloatWidths.x,
|
||||
TargetOffset.x,
|
||||
AnchorWidths.x);
|
||||
glm::vec3 p3 =
|
||||
YDirPosts ? GetPostsOffset(TFOR.Up(),
|
||||
FloatWidths.
|
||||
y) : GetExtentsOffset(TFOR.Up(),
|
||||
FloatWidths.y,
|
||||
TargetOffset.y,
|
||||
AnchorWidths.y);
|
||||
glm::vec3 p4 =
|
||||
ZDirPosts ? GetPostsOffset(TFOR.Back(),
|
||||
FloatWidths.
|
||||
z) : GetExtentsOffset(TFOR.Back(),
|
||||
FloatWidths.z,
|
||||
TargetOffset.z,
|
||||
AnchorWidths.z);
|
||||
|
||||
return p1 + p2 + p3 + p4;
|
||||
}
|
||||
|
||||
glm::vec3 ThirdPersonFollow::CalculateCenter()
|
||||
{
|
||||
return Target->get_global_translation() +
|
||||
TFOR.TransformDirection(Offset) + (mytransform->Back() * Distance);
|
||||
}
|
||||
|
||||
glm::vec3 ThirdPersonFollow::
|
||||
GetPostsOffset(const glm::vec3 & DirectionVector, float AnchorWidth)
|
||||
{
|
||||
float dot = glm::dot(Target->Forward(), DirectionVector);
|
||||
|
||||
return DirectionVector * (dot >= 0 ? AnchorWidth : AnchorWidth * -1);
|
||||
}
|
||||
|
||||
glm::vec3 ThirdPersonFollow::
|
||||
GetExtentsOffset(const glm::vec3 & DirectionVector, float AnchorWidth,
|
||||
float TOffset, float Width)
|
||||
{
|
||||
|
||||
float negated_offset_sign = ((0 <= TOffset) - (TOffset < 0)) * -1.f;
|
||||
float TotalWidth = AnchorWidth + Width;
|
||||
|
||||
if (glm::abs(TOffset) > TotalWidth
|
||||
&& !glm::epsilonEqual(glm::abs(TOffset), TotalWidth, 0.5f))
|
||||
return DirectionVector * TotalWidth * negated_offset_sign;
|
||||
else {
|
||||
if (glm::abs(TOffset) >= AnchorWidth)
|
||||
return DirectionVector * AnchorWidth * negated_offset_sign;
|
||||
else
|
||||
return DirectionVector * TOffset * -1.f;
|
||||
}
|
||||
|
||||
return glm::vec3(0.f);
|
||||
}
|
||||
|
||||
glm::vec3 ThirdPersonFollow::FrameBasedVectorLerp(const glm::vec3 & From,
|
||||
const glm::vec3 & To,
|
||||
const glm::vec3 & Speeds,
|
||||
float Tick)
|
||||
{
|
||||
// Previously "FORTransform.TransformVector(Speeds)
|
||||
glm::vec3 TSpeed = glm::abs(TFOR.TransformDirection(Speeds));
|
||||
glm::vec3 TOffset = glm::abs(TFOR.TransformDirection(TargetOffset));
|
||||
glm::vec3 TAnchorWidths =
|
||||
glm::abs(TFOR.TransformDirection(AnchorWidths));
|
||||
glm::vec3 TFloatWidths =
|
||||
glm::abs(TFOR.TransformDirection(FloatWidths));
|
||||
|
||||
|
||||
|
||||
// If these are true, that means to use the anchor speed instead of the normal speed.
|
||||
// True if the offset is beyond the anchor plus the width
|
||||
bool bUseX = GetLerpParam(TOffset.x, TAnchorWidths.x, TFloatWidths.x);
|
||||
bool bUseY = GetLerpParam(TOffset.y, TAnchorWidths.y, TFloatWidths.y);
|
||||
bool bUseZ = GetLerpParam(TOffset.z, TAnchorWidths.z, TFloatWidths.z);
|
||||
|
||||
|
||||
float xAlpha =
|
||||
glm::clamp((bUseX ? AnchorSpeed : TSpeed.x) * Tick, 0.f, 1.f);
|
||||
float yAlpha =
|
||||
glm::clamp((bUseY ? AnchorSpeed : TSpeed.y) * Tick, 0.f, 1.f);
|
||||
float zAlpha =
|
||||
glm::clamp((bUseZ ? AnchorSpeed : TSpeed.z) * Tick, 0.f, 1.f);
|
||||
|
||||
return VectorLerpPiecewise(From, To,
|
||||
glm::vec3(xAlpha, yAlpha, zAlpha));
|
||||
}
|
||||
|
||||
int float_epsilon(mfloat_t a, mfloat_t b, mfloat_t e)
|
||||
{
|
||||
return fabs(a - b) < e;
|
||||
}
|
||||
|
||||
int lerpparam(float offset, float anchorwidth, float floatwidth)
|
||||
{
|
||||
return (offset > (anchorwidth + floatwidth)) && !float_epsilon(anchorwidth + floatwidth, offset, 0.5f);
|
||||
}
|
||||
|
||||
mfloat_t *vec3lerp(mfloat_t from[3], mfloat_t to[3], mfloat_t a[3])
|
||||
{
|
||||
from[0] = from[0] + (to[0] - from[0]) * a[0];
|
||||
from[1] = from[1] + (to[1] - from[1]) * a[1];
|
||||
from[2] = from[2] + (to[2] - from[2]) * a[2];
|
||||
}
|
||||
|
||||
void follow_calctargets()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void ThirdPersonFollow::CalculateTargets()
|
||||
{
|
||||
// For translation
|
||||
TargetPosition = CalculatePosition();
|
||||
|
||||
|
||||
// For rotation
|
||||
// TODO: Check of this implementation is the same as UKismetMath FindLookAtRotation
|
||||
TargetRotation =
|
||||
RemoveLockedRotation(glm::quat
|
||||
(mytransform->
|
||||
get_global_transform()->get_origin() -
|
||||
Target->
|
||||
get_global_transform()->get_origin()));
|
||||
}
|
||||
|
||||
follow_removelockedrot()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
glm::quat ThirdPersonFollow::
|
||||
RemoveLockedRotation(const glm::quat & CurrentRotation)
|
||||
{
|
||||
glm::vec3 NewRotator;
|
||||
glm::vec3 CurrentRotator = glm::eulerAngles(CurrentRotation);
|
||||
//
|
||||
|
||||
NewRotator.x =
|
||||
LockRoll ? mytransform->get_rotation().x : CurrentRotator.x;
|
||||
NewRotator.y =
|
||||
LockPitch ? mytransform->get_rotation().y : CurrentRotator.y;
|
||||
NewRotator.z =
|
||||
LockYaw ? mytransform->get_rotation().z : CurrentRotator.z;
|
||||
|
||||
return glm::quat(NewRotator);
|
||||
}
|
||||
|
||||
// The target offset is the value of where the target is compared to where he "should" be based on where
|
||||
// the camera is. It is what the camera needs to move to be centered on the target
|
||||
void ThirdPersonFollow::CalculateTargetOffset()
|
||||
{
|
||||
glm::vec3 p1 =
|
||||
(mytransform->Forward() * Distance) +
|
||||
TFOR.TransformDirection(Offset) +
|
||||
mytransform->get_global_translation();
|
||||
glm::vec3 p2 =
|
||||
TFOR.InverseTransformDirection(Target->get_global_translation());
|
||||
glm::vec3 p3 = TFOR.InverseTransformDirection(p1);
|
||||
|
||||
TargetOffset = p2 - p3;
|
||||
}
|
||||
|
||||
void follow_targetoffset()
|
||||
{
|
||||
mfloat_t p1[3], p2[3], p3[3] = {0};
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
*/
|
||||
@@ -1,168 +0,0 @@
|
||||
#ifndef THIRDPERSONFOLLOW_H
|
||||
#define THIRDPERSONFOLLOW_H
|
||||
|
||||
#include "transform.h"
|
||||
#include "HandmadeMath.h"
|
||||
|
||||
/*
|
||||
|
||||
class ThirdPersonFollow {
|
||||
|
||||
public:
|
||||
enum CameraType {
|
||||
STATIONARY,
|
||||
TRANSLATING,
|
||||
ROTATING,
|
||||
SPLINE
|
||||
};
|
||||
|
||||
enum CameraTransition {
|
||||
NONE,
|
||||
CROSSDISSOLVE,
|
||||
WIPE,
|
||||
DIP
|
||||
};
|
||||
|
||||
enum FrameOfReference {
|
||||
LOCAL,
|
||||
WORLD,
|
||||
EXTERNAL
|
||||
};
|
||||
|
||||
ThirdPersonFollow() {
|
||||
// Rotation
|
||||
RotationSpeed = 10.0f;
|
||||
LockPitch = LockYaw = LockRoll = true;
|
||||
|
||||
XDirPosts = false;
|
||||
YDirPosts = false;
|
||||
ZDirPosts = false;
|
||||
|
||||
|
||||
// Translation
|
||||
//FloatWidths = AnchorWidths = CenterVector = glm::vec3(0, 0, 0);
|
||||
PositionSpeeds = glm::vec3(2.f, 2.f, 2.f);
|
||||
//TranslationScales = glm::vec3(1, 1, 1);
|
||||
|
||||
// Frame settings
|
||||
Offset = glm::vec3(0.f, 0.f, 0.f);
|
||||
Distance = 10;
|
||||
|
||||
AnchorSpeed = 80;
|
||||
} ~ThirdPersonFollow() {
|
||||
}
|
||||
|
||||
Transform *mytransform;
|
||||
|
||||
// An actor that can be given for the camera to base its movement around
|
||||
// instead of itself. Makes most sense for this to be stationary
|
||||
Transform *ExternalFrame = nullptr;
|
||||
|
||||
|
||||
void SetExternalFrame(Transform * val) {
|
||||
ExternalFrame = val;
|
||||
}
|
||||
|
||||
// The target the camera "looks" at, used for calculations
|
||||
Transform *Target = nullptr;
|
||||
|
||||
void SetTarget(Transform * val) {
|
||||
Target = val;
|
||||
}
|
||||
|
||||
// Offset from the target
|
||||
glm::vec3 Offset;
|
||||
|
||||
// How far away should the camera act from the target
|
||||
float Distance;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Translation variables. In this mode, the camera doesn't rotate to look
|
||||
// at the target, it only moves around the world.
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// "Posts" for each direction in 3D space. These are items that the target
|
||||
/// is allowed to move within without the camera following along.
|
||||
bool XDirPosts;
|
||||
bool YDirPosts;
|
||||
bool ZDirPosts;
|
||||
|
||||
/// The range in ecah direction the camera floats. While within this range,
|
||||
/// the camera will smoothly glide to the desired position.
|
||||
glm::vec3 FloatWidths;
|
||||
|
||||
/// The clamp range for each direction. If the camera reaches this range,
|
||||
/// it will stick and not move any further.
|
||||
glm::vec3 AnchorWidths;
|
||||
|
||||
/// When floating to the target, the speed to float.
|
||||
glm::vec3 PositionSpeeds;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Rotation variables. Used for the camera's rotation mode, where it
|
||||
// follows the Target without translating.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Variables to lock its rotation in any of the three directions
|
||||
bool LockRoll;
|
||||
bool LockPitch;
|
||||
bool LockYaw;
|
||||
|
||||
glm::vec3 RotationOffset;
|
||||
|
||||
/// The speed of rotation
|
||||
float RotationSpeed;
|
||||
|
||||
private:
|
||||
void CalculateTargetOffset();
|
||||
|
||||
// Transform of frame of reference
|
||||
Transform TFOR;
|
||||
|
||||
/// The calculated offset based on frames of reference
|
||||
glm::vec3 TargetOffset;
|
||||
|
||||
glm::vec3 TargetPosition;
|
||||
|
||||
glm::quat TargetRotation;
|
||||
|
||||
|
||||
void CalculateTargets();
|
||||
|
||||
// Calculates
|
||||
|
||||
glm::vec3 CalculatePosition();
|
||||
|
||||
glm::vec3 CalculateCenter();
|
||||
|
||||
/// Given a direction and width, find the offsets.
|
||||
glm::vec3 GetPostsOffset(const glm::vec3 & DirectionVector,
|
||||
float AnchorWidth);
|
||||
|
||||
/// Given anchors, what's the anchor width?
|
||||
glm::vec3 GetExtentsOffset(const glm::vec3 & DirectionVector,
|
||||
float AnchorWidth, float TOffset,
|
||||
float Width);
|
||||
|
||||
glm::quat RemoveLockedRotation(const glm::quat & CurrentRotation);
|
||||
|
||||
glm::vec3 FrameBasedVectorLerp(const glm::vec3 & From,
|
||||
const glm::vec3 & To,
|
||||
const glm::vec3 & Speeds, float Tick);
|
||||
|
||||
glm::vec3 VectorLerpPiecewise(const glm::vec3 & From,
|
||||
const glm::vec3 & To,
|
||||
const glm::vec3 & Alpha);
|
||||
|
||||
bool GetLerpParam(const float Offst, const float AnchorWidth,
|
||||
const float FloatWidth);
|
||||
|
||||
/// Set to a value that gives good clamping, smoothly. Activates when
|
||||
/// the target is out of range.
|
||||
float AnchorSpeed;
|
||||
|
||||
};
|
||||
|
||||
*/
|
||||
|
||||
#endif
|
||||
@@ -1,63 +0,0 @@
|
||||
#include "anim.h"
|
||||
#include "stb_ds.h"
|
||||
|
||||
void animation_run(struct animation *anim, float now)
|
||||
{
|
||||
float elapsed = now - anim->time;
|
||||
elapsed = fmod(elapsed,2);
|
||||
if (!anim->channels) return;
|
||||
|
||||
for (int i = 0; i < arrlen(anim->channels); i++) {
|
||||
struct anim_channel *ch = anim->channels+i;
|
||||
HMM_Vec4 s = sample_sampler(ch->sampler, elapsed);
|
||||
*(ch->target) = s;
|
||||
}
|
||||
}
|
||||
|
||||
HMM_Vec4 sample_cubicspline(sampler *sampler, float t, int prev, int next)
|
||||
{
|
||||
HMM_Vec4 ret;
|
||||
HMM_Quat qv = HMM_SLerp(HMM_QV4(sampler->data[prev]), t, HMM_QV4(sampler->data[next]));
|
||||
memcpy(ret.e, qv.e, sizeof(ret.e));
|
||||
return ret;
|
||||
}
|
||||
|
||||
HMM_Vec4 sample_sampler(sampler *sampler, float time)
|
||||
{
|
||||
if (arrlen(sampler->data) == 0) return v4zero;
|
||||
if (arrlen(sampler->data) == 1) return sampler->data[0];
|
||||
int previous_time=0;
|
||||
int next_time=0;
|
||||
|
||||
for (int i = 1; i < arrlen(sampler->times); i++) {
|
||||
if (time < sampler->times[i]) {
|
||||
previous_time = i-1;
|
||||
next_time = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
float td = sampler->times[next_time]-sampler->times[previous_time];
|
||||
float t = (time - sampler->times[previous_time])/td;
|
||||
|
||||
HMM_Vec4 ret;
|
||||
HMM_Quat qv;
|
||||
|
||||
switch(sampler->type) {
|
||||
case LINEAR:
|
||||
return HMM_LerpV4(sampler->data[previous_time],time,sampler->data[next_time]);
|
||||
break;
|
||||
case STEP:
|
||||
return sampler->data[previous_time];
|
||||
break;
|
||||
case CUBICSPLINE:
|
||||
return sample_cubicspline(sampler,t, previous_time, next_time);
|
||||
break;
|
||||
case SLERP:
|
||||
qv = HMM_SLerp(sampler->data[previous_time].quat, time, sampler->data[next_time].quat);
|
||||
memcpy(ret.e,qv.e,sizeof(ret.e));
|
||||
return ret;
|
||||
break;
|
||||
}
|
||||
return sample_cubicspline(sampler,t, previous_time, next_time);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
#ifndef ANIM_H
|
||||
#define ANIM_H
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
|
||||
struct keyframe {
|
||||
double time;
|
||||
double val;
|
||||
};
|
||||
|
||||
#define LINEAR 0
|
||||
#define STEP 1
|
||||
#define CUBICSPLINE 2
|
||||
#define SLERP 3
|
||||
|
||||
typedef struct sampler {
|
||||
float *times;
|
||||
HMM_Vec4 *data;
|
||||
int type;
|
||||
} sampler;
|
||||
|
||||
struct anim_channel {
|
||||
HMM_Vec4 *target;
|
||||
int comps;
|
||||
struct sampler *sampler;
|
||||
};
|
||||
|
||||
typedef struct animation {
|
||||
double time;
|
||||
struct anim_channel *channels;
|
||||
sampler *samplers;
|
||||
} animation;
|
||||
|
||||
void animation_run(struct animation *anim, float now);
|
||||
HMM_Vec4 sample_sampler(sampler *sampler, float time);
|
||||
|
||||
#endif
|
||||
@@ -33,8 +33,9 @@
|
||||
#define BLOB_IMPLEMENTATION
|
||||
#include "blob.h"
|
||||
|
||||
#include "physfs.h"
|
||||
#define STB_DS_IMPLEMENTATION
|
||||
#include "stb_ds.h"
|
||||
|
||||
#include "jsffi.h"
|
||||
#include "cell.h"
|
||||
#include "timer.h"
|
||||
|
||||
@@ -93,8 +93,6 @@ mi_heap_t *heap;
|
||||
const char *name; // human friendly name
|
||||
} cell_rt;
|
||||
|
||||
extern SDL_TLSID prosperon_id;
|
||||
|
||||
extern cell_rt *root_cell; // first actor in the system
|
||||
|
||||
cell_rt *create_actor(void *wota);
|
||||
@@ -115,8 +113,6 @@ void actor_clock(cell_rt *actor, JSValue fn);
|
||||
|
||||
int JS_ArrayLength(JSContext *js, JSValue a);
|
||||
|
||||
int prosperon_mount_core(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
#define QOI_IMPLEMENTATION
|
||||
#include "qoi.h"
|
||||
#include "cell.h"
|
||||
#include "qjs_sdl.h"
|
||||
#include <SDL3/SDL.h>
|
||||
#include <string.h>
|
||||
|
||||
// Helper function to check for integer overflow in size calculations
|
||||
static int check_size_overflow(size_t a, size_t b, size_t c, size_t *result)
|
||||
{
|
||||
if (a > SIZE_MAX / b) return 1;
|
||||
size_t temp = a * b;
|
||||
if (temp > SIZE_MAX / c) return 1;
|
||||
*result = temp * c;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// QOI compression/encoding
|
||||
JSValue js_qoi_encode(JSContext *js, JSValue this_val, int argc, JSValueConst *argv)
|
||||
{
|
||||
if (argc < 1)
|
||||
return JS_ThrowTypeError(js, "compress_qoi requires an object argument");
|
||||
|
||||
// Check if width/height properties exist
|
||||
JSValue width_val = JS_GetPropertyStr(js, argv[0], "width");
|
||||
JSValue height_val = JS_GetPropertyStr(js, argv[0], "height");
|
||||
|
||||
if (JS_IsNull(width_val) || JS_IsNull(height_val)) {
|
||||
JS_FreeValue(js, width_val);
|
||||
JS_FreeValue(js, height_val);
|
||||
return JS_ThrowTypeError(js, "compress_qoi requires width and height properties");
|
||||
}
|
||||
|
||||
int width, height;
|
||||
if (JS_ToInt32(js, &width, width_val) < 0 || JS_ToInt32(js, &height, height_val) < 0) {
|
||||
JS_FreeValue(js, width_val);
|
||||
JS_FreeValue(js, height_val);
|
||||
return JS_ThrowTypeError(js, "width and height must be numbers");
|
||||
}
|
||||
JS_FreeValue(js, width_val);
|
||||
JS_FreeValue(js, height_val);
|
||||
|
||||
if (width < 1 || height < 1)
|
||||
return JS_ThrowRangeError(js, "width and height must be at least 1");
|
||||
|
||||
// Get pixel format
|
||||
JSValue format_val = JS_GetPropertyStr(js, argv[0], "format");
|
||||
SDL_PixelFormat format = js2SDL_PixelFormat(js, format_val);
|
||||
JS_FreeValue(js, format_val);
|
||||
|
||||
if (format == SDL_PIXELFORMAT_UNKNOWN)
|
||||
return JS_ThrowTypeError(js, "Invalid or missing pixel format");
|
||||
|
||||
// Get pixels
|
||||
JSValue pixels_val = JS_GetPropertyStr(js, argv[0], "pixels");
|
||||
size_t pixel_len;
|
||||
void *pixel_data = js_get_blob_data(js, &pixel_len, pixels_val);
|
||||
JS_FreeValue(js, pixels_val);
|
||||
|
||||
if (!pixel_data)
|
||||
return JS_ThrowTypeError(js, "pixels property must be a stoned blob");
|
||||
|
||||
// Validate buffer size
|
||||
int bytes_per_pixel = SDL_BYTESPERPIXEL(format);
|
||||
size_t required_size;
|
||||
if (check_size_overflow(width, height, bytes_per_pixel, &required_size)) {
|
||||
JS_FreeValue(js, pixels_val);
|
||||
return JS_ThrowRangeError(js, "Image dimensions too large");
|
||||
}
|
||||
|
||||
if (pixel_len < required_size)
|
||||
return JS_ThrowRangeError(js, "pixels buffer too small for %dx%d format (need %zu bytes, got %zu)",
|
||||
width, height, required_size, pixel_len);
|
||||
|
||||
// Get colorspace (optional, default to sRGB)
|
||||
int colorspace = 0; // QOI_SRGB
|
||||
if (argc > 1) {
|
||||
colorspace = JS_ToBool(js, argv[1]);
|
||||
}
|
||||
|
||||
// Determine number of channels based on format
|
||||
int channels = SDL_ISPIXELFORMAT_ALPHA(format) ? 4 : 3;
|
||||
|
||||
// Prepare QOI descriptor
|
||||
qoi_desc desc = {
|
||||
.width = width,
|
||||
.height = height,
|
||||
.channels = channels,
|
||||
.colorspace = colorspace
|
||||
};
|
||||
|
||||
// Encode to QOI
|
||||
int out_len;
|
||||
void *qoi_data = qoi_encode(pixel_data, &desc, &out_len);
|
||||
|
||||
if (!qoi_data)
|
||||
return JS_ThrowInternalError(js, "QOI encoding failed");
|
||||
|
||||
// Create result object
|
||||
JSValue result = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, result, "width", JS_NewInt32(js, width));
|
||||
JS_SetPropertyStr(js, result, "height", JS_NewInt32(js, height));
|
||||
JS_SetPropertyStr(js, result, "format", JS_NewString(js, "qoi"));
|
||||
JS_SetPropertyStr(js, result, "channels", JS_NewInt32(js, channels));
|
||||
JS_SetPropertyStr(js, result, "colorspace", JS_NewInt32(js, colorspace));
|
||||
|
||||
JSValue compressed_pixels = js_new_blob_stoned_copy(js, qoi_data, out_len);
|
||||
free(qoi_data); // Free the QOI buffer after copying to blob
|
||||
JS_SetPropertyStr(js, result, "pixels", compressed_pixels);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// QOI decompression/decoding
|
||||
JSValue js_qoi_decode(JSContext *js, JSValue this_val, int argc, JSValueConst *argv)
|
||||
{
|
||||
size_t len;
|
||||
void *raw = js_get_blob_data(js, &len, argv[0]);
|
||||
if (!raw) return JS_ThrowReferenceError(js, "could not get QOI data from array buffer");
|
||||
|
||||
qoi_desc desc;
|
||||
void *data = qoi_decode(raw, len, &desc, 0); // 0 means use channels from file
|
||||
|
||||
if (!data)
|
||||
return JS_NULL; // Return null if not valid QOI
|
||||
|
||||
// QOI always decodes to either RGB or RGBA based on the file's channel count
|
||||
int channels = desc.channels;
|
||||
int pitch = desc.width * channels;
|
||||
size_t pixels_size = pitch * desc.height;
|
||||
|
||||
// If it's RGB, convert to RGBA for consistency
|
||||
void *rgba_data = data;
|
||||
if (channels == 3) {
|
||||
rgba_data = malloc(desc.width * desc.height * 4);
|
||||
if (!rgba_data) {
|
||||
free(data);
|
||||
return JS_ThrowOutOfMemory(js);
|
||||
}
|
||||
|
||||
// Convert RGB to RGBA
|
||||
unsigned char *src = (unsigned char*)data;
|
||||
unsigned char *dst = (unsigned char*)rgba_data;
|
||||
for (int i = 0; i < desc.width * desc.height; i++) {
|
||||
dst[i*4] = src[i*3];
|
||||
dst[i*4+1] = src[i*3+1];
|
||||
dst[i*4+2] = src[i*3+2];
|
||||
dst[i*4+3] = 255;
|
||||
}
|
||||
free(data);
|
||||
pitch = desc.width * 4;
|
||||
pixels_size = pitch * desc.height;
|
||||
}
|
||||
|
||||
// Create JS object with surface data
|
||||
JSValue obj = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, obj, "width", JS_NewInt32(js, desc.width));
|
||||
JS_SetPropertyStr(js, obj, "height", JS_NewInt32(js, desc.height));
|
||||
JS_SetPropertyStr(js, obj, "format", JS_NewString(js, "rgba32"));
|
||||
JS_SetPropertyStr(js, obj, "pitch", JS_NewInt32(js, pitch));
|
||||
JS_SetPropertyStr(js, obj, "pixels", js_new_blob_stoned_copy(js, rgba_data, pixels_size));
|
||||
JS_SetPropertyStr(js, obj, "depth", JS_NewInt32(js, 8));
|
||||
JS_SetPropertyStr(js, obj, "hdr", JS_NewBool(js, 0));
|
||||
JS_SetPropertyStr(js, obj, "colorspace", JS_NewInt32(js, desc.colorspace));
|
||||
|
||||
free(rgba_data);
|
||||
return obj;
|
||||
}
|
||||
|
||||
static const JSCFunctionListEntry js_qoi_funcs[] = {
|
||||
MIST_FUNC_DEF(qoi, encode, 1),
|
||||
MIST_FUNC_DEF(qoi, decode, 1)
|
||||
};
|
||||
|
||||
JSValue js_qoi_use(JSContext *js)
|
||||
{
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, mod, js_qoi_funcs, countof(js_qoi_funcs));
|
||||
return mod;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
#include "render.h"
|
||||
|
||||
#define CUTE_ASEPRITE_IMPLEMENTATION
|
||||
#include "cute_aseprite.h"
|
||||
|
||||
#define STB_PERLIN_IMPLEMENTATION
|
||||
#include "stb_perlin.h"
|
||||
|
||||
#define STB_RECT_PACK_IMPLEMENTATION
|
||||
#include "stb_rect_pack.h"
|
||||
|
||||
#define STB_HEXWAVE_IMPLEMENTATION
|
||||
#include "stb_hexwave.h"
|
||||
|
||||
#define STB_DS_IMPLEMENTATION
|
||||
#include <stb_ds.h>
|
||||
|
||||
#define STB_TRUETYPE_IMPLEMENTATION
|
||||
#define STB_TRUETYPE_NO_STDIO
|
||||
#include <stb_truetype.h>
|
||||
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#define STBI_FAILURE_USERMSG
|
||||
#define STBI_NO_STDIO
|
||||
#include "stb_image.h"
|
||||
|
||||
#define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_BOX
|
||||
|
||||
#define STB_IMAGE_WRITE_IMPLEMENTATION
|
||||
#include "stb_image_write.h"
|
||||
|
||||
#define PL_MPEG_IMPLEMENTATION
|
||||
#include <pl_mpeg.h>
|
||||
|
||||
#define NANOSVG_IMPLEMENTATION
|
||||
#define NANOSVGRAST_IMPLEMENTATION
|
||||
#include "nanosvg.h"
|
||||
#include "nanosvgrast.h"
|
||||
|
||||
#define CGLTF_IMPLEMENTATION
|
||||
#include "cgltf.h"
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,44 +0,0 @@
|
||||
#include "datastream.h"
|
||||
|
||||
#include "limits.h"
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include "font.h"
|
||||
#include "render.h"
|
||||
#include <string.h>
|
||||
|
||||
#include "cbuf.h"
|
||||
|
||||
void datastream_free(JSRuntime *rt,datastream *ds)
|
||||
{
|
||||
plm_destroy(ds->plm);
|
||||
free(ds);
|
||||
}
|
||||
|
||||
struct datastream *ds_openvideo(void *raw, size_t rawlen)
|
||||
{
|
||||
struct datastream *ds = malloc(sizeof(*ds));
|
||||
void *newraw = malloc(rawlen);
|
||||
memcpy(newraw,raw,rawlen);
|
||||
ds->plm = plm_create_with_memory(newraw, rawlen, 1);
|
||||
|
||||
if (!ds->plm) {
|
||||
free(ds);
|
||||
free(newraw);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return ds;
|
||||
}
|
||||
|
||||
void ds_advance(struct datastream *ds, double s) {
|
||||
plm_decode(ds->plm, s);
|
||||
}
|
||||
|
||||
void ds_seek(struct datastream *ds, double time) {
|
||||
plm_seek(ds->plm, time, false);
|
||||
}
|
||||
|
||||
double ds_length(struct datastream *ds) {
|
||||
return plm_get_duration(ds->plm);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
#ifndef DATASTREAM_H
|
||||
#define DATASTREAM_H
|
||||
|
||||
#include <pl_mpeg.h>
|
||||
#include <stdint.h>
|
||||
#include "cell.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
struct datastream {
|
||||
plm_t *plm;
|
||||
JSValue callback;
|
||||
JSContext *js;
|
||||
int width;
|
||||
int height;
|
||||
};
|
||||
|
||||
typedef struct datastream datastream;
|
||||
|
||||
void datastream_free(JSRuntime *rt,datastream *ds);
|
||||
|
||||
struct datastream *ds_openvideo(void *raw, size_t rawlen);
|
||||
void ds_advance(struct datastream *ds, double); // advance time in seconds
|
||||
void ds_seek(struct datastream *ds, double);
|
||||
void ds_pause(struct datastream *ds);
|
||||
void ds_stop(struct datastream *ds);
|
||||
int ds_videodone(struct datastream *ds);
|
||||
double ds_remainingtime(struct datastream *ds);
|
||||
double ds_length(struct datastream *ds);
|
||||
|
||||
#endif
|
||||
1776
source/dmon.h
1776
source/dmon.h
File diff suppressed because it is too large
Load Diff
320
source/font.c
320
source/font.c
@@ -1,320 +0,0 @@
|
||||
#include "font.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "render.h"
|
||||
|
||||
#include "stb_image_write.h"
|
||||
#include "stb_rect_pack.h"
|
||||
#include "stb_truetype.h"
|
||||
#include "stb_ds.h"
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
|
||||
typedef struct { const char *start, *end; float width; } line_t;
|
||||
typedef struct { line_t *lines; float max_width; } layout_lines;
|
||||
|
||||
struct sFont *use_font;
|
||||
|
||||
void font_free(JSRuntime *rt, font *f)
|
||||
{
|
||||
if (f->surface) SDL_DestroySurface(f->surface);
|
||||
free(f);
|
||||
}
|
||||
|
||||
struct sFont *MakeFont(void *ttf_buffer, size_t len, int height) {
|
||||
if (!ttf_buffer)
|
||||
return NULL;
|
||||
|
||||
int packsize = 1024;
|
||||
|
||||
struct sFont *newfont = calloc(1, sizeof(struct sFont));
|
||||
newfont->height = height;
|
||||
|
||||
unsigned char *bitmap = malloc(packsize * packsize);
|
||||
|
||||
stbtt_packedchar glyphs[95];
|
||||
|
||||
stbtt_pack_context pc;
|
||||
|
||||
int pad = 2;
|
||||
|
||||
stbtt_PackBegin(&pc, bitmap, packsize, packsize, 0, pad, NULL);
|
||||
stbtt_PackFontRange(&pc, ttf_buffer, 0, height, 32, 95, glyphs);
|
||||
stbtt_PackEnd(&pc);
|
||||
|
||||
stbtt_fontinfo fontinfo;
|
||||
if (!stbtt_InitFont(&fontinfo, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer, 0))) {
|
||||
// YughError("Failed to make font %s", fontfile);
|
||||
}
|
||||
|
||||
int ascent, descent, linegap;
|
||||
|
||||
stbtt_GetFontVMetrics(&fontinfo, &ascent, &descent, &linegap);
|
||||
float s = stbtt_ScaleForPixelHeight(&fontinfo, height);
|
||||
newfont->ascent = ascent * s;
|
||||
newfont->descent = descent * s; /* descent is negative */
|
||||
newfont->linegap = linegap * s;
|
||||
newfont->line_height = (newfont->ascent - newfont->descent) + newfont->linegap;
|
||||
newfont->surface = SDL_CreateSurface(packsize,packsize, SDL_PIXELFORMAT_RGBA32);
|
||||
if (!newfont->surface) printf("SDL ERROR: %s\n", SDL_GetError());
|
||||
for (int i = 0; i < packsize; i++)
|
||||
for (int j = 0; j < packsize; j++)
|
||||
if (!SDL_WriteSurfacePixel(newfont->surface, j, i, 255,255,255,bitmap[i*packsize+j]))
|
||||
printf("SDLERROR: %s\n", SDL_GetError());
|
||||
|
||||
for (unsigned char c = 32; c < 127; c++) {
|
||||
stbtt_packedchar glyph = glyphs[c - 32];
|
||||
|
||||
rect uv;
|
||||
uv.x = (glyph.x0) / (float)packsize;
|
||||
uv.w = (glyph.x1-glyph.x0) / (float)packsize;
|
||||
uv.y = (glyph.y1) / (float)packsize;
|
||||
uv.h = (glyph.y0-glyph.y1) / (float)packsize;
|
||||
newfont->Characters[c].uv = uv;
|
||||
|
||||
rect quad;
|
||||
quad.x = glyph.xoff;
|
||||
quad.y = -glyph.yoff2; // Top of glyph relative to baseline
|
||||
quad.w = glyph.xoff2 - glyph.xoff;
|
||||
quad.h = glyph.yoff2 - glyph.yoff; // Height from baseline
|
||||
newfont->Characters[c].quad = quad;
|
||||
newfont->Characters[c].advance = glyph.xadvance;
|
||||
}
|
||||
|
||||
free(bitmap);
|
||||
|
||||
return newfont;
|
||||
}
|
||||
|
||||
layout_lines layout_text_lines(const char *text, font *f,
|
||||
float letter_spacing,
|
||||
float wrap,
|
||||
TEXT_BREAK break_at)
|
||||
{
|
||||
layout_lines out = {0};
|
||||
int break_at_word = (break_at == WORD);
|
||||
|
||||
const char *line_start = text;
|
||||
const char *word_start = text;
|
||||
float line_width = 0;
|
||||
float word_width = 0;
|
||||
|
||||
float max_width = 0;
|
||||
|
||||
for (const char *p = text; *p; p++) {
|
||||
if (*p == '\n') {
|
||||
line_t L = { line_start, p, line_width };
|
||||
arrput(out.lines, L);
|
||||
if (line_width > max_width) max_width = line_width;
|
||||
|
||||
line_start = p + 1;
|
||||
word_start = p + 1;
|
||||
line_width = 0;
|
||||
word_width = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char ch = (unsigned char)*p;
|
||||
float char_w = f->Characters[ch].advance + letter_spacing;
|
||||
|
||||
if (wrap > 0 && line_width + char_w > wrap) {
|
||||
const char *break_pt = p;
|
||||
float break_w = line_width;
|
||||
|
||||
if (break_at_word && *p != ' ' && word_width > 0 && word_start > line_start) {
|
||||
break_pt = word_start;
|
||||
break_w = line_width - word_width;
|
||||
}
|
||||
|
||||
line_t L = { line_start, break_pt, break_w };
|
||||
arrput(out.lines, L);
|
||||
if (break_w > max_width) max_width = break_w;
|
||||
|
||||
line_start = break_pt;
|
||||
if (break_at_word && *line_start == ' ') line_start++;
|
||||
|
||||
p = line_start - 1;
|
||||
word_start = line_start;
|
||||
line_width = 0;
|
||||
word_width = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
line_width += char_w;
|
||||
|
||||
if (break_at_word) {
|
||||
if (*p == ' ') {
|
||||
word_width = 0;
|
||||
word_start = p + 1;
|
||||
} else {
|
||||
word_width += char_w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (line_start < text + strlen(text)) {
|
||||
line_t L = { line_start, text + strlen(text), line_width };
|
||||
arrput(out.lines, L);
|
||||
if (line_width > max_width) max_width = line_width;
|
||||
}
|
||||
|
||||
out.max_width = max_width;
|
||||
return out;
|
||||
}
|
||||
|
||||
void sdrawCharacter(struct text_vert **buffer, stbtt_packedchar c, HMM_Vec2 cursor, float scale, struct rgba color) {
|
||||
struct text_vert vert;
|
||||
|
||||
// vert.pos.x = cursor.X + c.leftbearing;
|
||||
// vert.pos.y = cursor.Y + c.topbearing;
|
||||
// vert.wh = c.size;
|
||||
|
||||
// if (vert.pos.x > frame.l || vert.pos.y > frame.t || (vert.pos.y + vert.wh.y) < frame.b || (vert.pos.x + vert.wh.x) < frame.l) return;
|
||||
|
||||
// vert.uv.x = c.rect.x;
|
||||
// vert.uv.y = c.rect.y;
|
||||
// vert.st.x = c.rect.w;
|
||||
// vert.st.y = c.rect.h;
|
||||
rgba2floats(vert.color.e, color);
|
||||
|
||||
arrput(*buffer, vert);
|
||||
}
|
||||
|
||||
void draw_char_verts(struct text_vert **buffer, struct character c, HMM_Vec2 cursor, colorf color)
|
||||
{
|
||||
// packedchar has
|
||||
// Adds four verts: bottom left, bottom right, top left, top right
|
||||
text_vert bl;
|
||||
bl.pos.x = cursor.X + c.quad.x;
|
||||
bl.pos.y = cursor.Y + c.quad.y;
|
||||
bl.uv.x = c.uv.x;
|
||||
bl.uv.y = c.uv.y;
|
||||
bl.color = color;
|
||||
arrput(*buffer, bl);
|
||||
|
||||
|
||||
text_vert br = bl;
|
||||
br.pos.x += c.quad.w;
|
||||
br.uv.x += c.uv.w;
|
||||
arrput(*buffer, br);
|
||||
|
||||
text_vert ul = bl;
|
||||
ul.pos.y += c.quad.h;
|
||||
ul.uv.y += c.uv.h;
|
||||
arrput(*buffer, ul);
|
||||
|
||||
text_vert ur = ul;
|
||||
ur.pos.x = br.pos.x;
|
||||
ur.uv.x = br.uv.x;
|
||||
arrput(*buffer, ur);
|
||||
}
|
||||
|
||||
const char *esc_color(const char *c, struct rgba *color, struct rgba defc)
|
||||
{
|
||||
struct rgba d;
|
||||
if (!color) color = &d;
|
||||
if (*c != '\033') return c;
|
||||
c++;
|
||||
if (*c != '[') return c;
|
||||
c++;
|
||||
if (*c == '0') {
|
||||
*color = defc;
|
||||
c++;
|
||||
return c;
|
||||
}
|
||||
else if (!strncmp(c, "38;2;", 5)) {
|
||||
c += 5;
|
||||
*color = (struct rgba){0,0,0,255};
|
||||
color->r = atoi(c);
|
||||
c = strchr(c, ';')+1;
|
||||
color->g = atoi(c);
|
||||
c = strchr(c,';')+1;
|
||||
color->b = atoi(c);
|
||||
c = strchr(c,';')+1;
|
||||
return c;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// text is a string, font f, wrap is how long a line is before wrapping. -1 to not wrap
|
||||
HMM_Vec2 measure_text(const char *text, font *f, float letter_spacing, float wrap, TEXT_BREAK break_at, TEXT_ALIGN align)
|
||||
{
|
||||
layout_lines lay = layout_text_lines(text, f, letter_spacing, wrap, break_at);
|
||||
|
||||
float lh = f->line_height;
|
||||
int line_count = arrlen(lay.lines);
|
||||
float height = line_count > 0 ? line_count * lh : 0;
|
||||
|
||||
float width = lay.max_width;
|
||||
if (wrap > 0 && align != LEFT && align != JUSTIFY) {
|
||||
// For RIGHT or CENTER we might shift lines visually, but width is still max(line.width, wrap ? min(wrap, ...) ).
|
||||
// Usually you'd report max(wrap, width) or just wrap, depending on how you want containers to size.
|
||||
}
|
||||
|
||||
HMM_Vec2 dim = { width, height };
|
||||
|
||||
arrfree(lay.lines);
|
||||
return dim;
|
||||
}
|
||||
|
||||
/* pos given in screen coordinates */
|
||||
struct text_vert *renderText(const char *text, HMM_Vec2 pos, font *f, colorf color,
|
||||
float wrap, TEXT_BREAK break_at, TEXT_ALIGN align,
|
||||
float letter_spacing)
|
||||
{
|
||||
text_vert *buffer = NULL;
|
||||
float lh = f->line_height;
|
||||
|
||||
layout_lines lay = layout_text_lines(text, f, letter_spacing, wrap, break_at);
|
||||
line_t *lines = lay.lines;
|
||||
|
||||
HMM_Vec2 cursor = pos;
|
||||
|
||||
for (int i = 0; i < arrlen(lines); i++) {
|
||||
line_t *L = &lines[i];
|
||||
float start_x = pos.x;
|
||||
float extra_space = 0;
|
||||
int space_count = 0;
|
||||
|
||||
if (wrap > 0) {
|
||||
switch (align) {
|
||||
case RIGHT: start_x = pos.x + wrap - L->width; break;
|
||||
case CENTER: start_x = pos.x + (wrap - L->width) * 0.5f; break;
|
||||
case JUSTIFY:
|
||||
if (i < arrlen(lines) - 1 && *(L->end) != '\n') {
|
||||
for (const char *p = L->start; p < L->end; p++) if (*p == ' ') space_count++;
|
||||
if (space_count > 0) extra_space = (wrap - L->width) / space_count;
|
||||
}
|
||||
break;
|
||||
case LEFT: default: break;
|
||||
}
|
||||
}
|
||||
|
||||
cursor.x = start_x;
|
||||
|
||||
const char *p = L->start;
|
||||
while (p < L->end) {
|
||||
unsigned char ch = (unsigned char)*p;
|
||||
struct character g = f->Characters[ch];
|
||||
|
||||
if (!isspace(*p)) draw_char_verts(&buffer, g, cursor, color);
|
||||
|
||||
cursor.x += g.advance;
|
||||
/* add letter spacing unless this is last char of the line */
|
||||
if (p + 1 < L->end) cursor.x += letter_spacing;
|
||||
if (align == JUSTIFY && *p == ' ') cursor.x += extra_space;
|
||||
|
||||
p++;
|
||||
}
|
||||
|
||||
cursor.x = pos.x;
|
||||
cursor.y -= lh;
|
||||
}
|
||||
|
||||
arrfree(lines);
|
||||
return buffer;
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
#ifndef FONT_H
|
||||
#define FONT_H
|
||||
|
||||
#include "render.h"
|
||||
#include "HandmadeMath.h"
|
||||
#include "cell.h"
|
||||
#include <SDL3/SDL.h>
|
||||
#include "render.h"
|
||||
|
||||
typedef enum {
|
||||
LEFT,
|
||||
RIGHT,
|
||||
CENTER,
|
||||
JUSTIFY
|
||||
} TEXT_ALIGN;
|
||||
|
||||
typedef enum {
|
||||
WORD,
|
||||
CHARACTER
|
||||
} TEXT_BREAK;
|
||||
|
||||
struct text_vert {
|
||||
HMM_Vec2 pos;
|
||||
HMM_Vec2 uv;
|
||||
HMM_Vec4 color;
|
||||
};
|
||||
|
||||
typedef struct text_vert text_vert;
|
||||
|
||||
struct text_char {
|
||||
rect pos;
|
||||
rect uv;
|
||||
HMM_Vec4 color;
|
||||
};
|
||||
|
||||
struct shader;
|
||||
struct window;
|
||||
|
||||
struct character {
|
||||
float advance;
|
||||
rect quad;
|
||||
rect uv;
|
||||
float xoff;
|
||||
float yoff;
|
||||
float width;
|
||||
float height;
|
||||
};
|
||||
|
||||
// text data
|
||||
struct sFont {
|
||||
uint32_t height; /* in pixels */
|
||||
float ascent; // pixels
|
||||
float descent; // pixels
|
||||
float linegap; //pixels
|
||||
float line_height; // pixels
|
||||
struct character Characters[256];
|
||||
SDL_Surface *surface;
|
||||
};
|
||||
|
||||
typedef struct sFont font;
|
||||
typedef struct Character glyph;
|
||||
|
||||
void font_free(JSRuntime *rt,font *f);
|
||||
|
||||
struct sFont *MakeFont(void *data, size_t len, int height);
|
||||
struct text_vert *renderText(const char *text, HMM_Vec2 pos, font *f, colorf color, float wrap, TEXT_BREAK breakAt, TEXT_ALIGN align, float letter_spacing);
|
||||
HMM_Vec2 measure_text(const char *text, font *f, float letterSpacing, float wrap, TEXT_BREAK breakAt, TEXT_ALIGN align);
|
||||
|
||||
#endif
|
||||
343
source/jsffi.c
343
source/jsffi.c
@@ -1,10 +1,5 @@
|
||||
#include "jsffi.h"
|
||||
#include "font.h"
|
||||
#include "datastream.h"
|
||||
#include "transform.h"
|
||||
#include "stb_ds.h"
|
||||
#include "stb_image.h"
|
||||
#include "stb_rect_pack.h"
|
||||
#include "string.h"
|
||||
#include <assert.h>
|
||||
#include <time.h>
|
||||
@@ -13,10 +8,8 @@
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <limits.h>
|
||||
#include "render.h"
|
||||
#include "HandmadeMath.h"
|
||||
#include <stdint.h>
|
||||
#include "cute_aseprite.h"
|
||||
#include "cell.h"
|
||||
|
||||
#include "qjs_wota.h"
|
||||
@@ -27,11 +20,6 @@
|
||||
#include <dlfcn.h>
|
||||
#endif
|
||||
|
||||
// External transform function declarations
|
||||
extern JSClassID js_transform_id;
|
||||
JSValue transform2js(JSContext *js, transform *t);
|
||||
transform *js2transform(JSContext *js, JSValue v);
|
||||
|
||||
// Random number generation constants for MT19937-64
|
||||
#define NN STATE_VECTOR_LENGTH
|
||||
#define MM STATE_VECTOR_M
|
||||
@@ -188,68 +176,7 @@ JSValue make_quad_indices_buffer(JSContext *js, int quads)
|
||||
return JS_DupValue(js,rt->idx_buffer);
|
||||
}
|
||||
|
||||
JSValue quads_to_mesh(JSContext *js, text_vert *buffer)
|
||||
{
|
||||
size_t verts = arrlen(buffer);
|
||||
|
||||
JSValue ret = JS_NewObject(js);
|
||||
|
||||
// Allocate flat arrays for xy, uv, and color data
|
||||
size_t xy_size = verts * 2 * sizeof(float);
|
||||
size_t uv_size = verts * 2 * sizeof(float);
|
||||
size_t color_size = verts * sizeof(SDL_FColor);
|
||||
|
||||
float *xy_data = malloc(xy_size);
|
||||
float *uv_data = malloc(uv_size);
|
||||
SDL_FColor *color_data = malloc(color_size);
|
||||
|
||||
// Convert vertex data to flat arrays
|
||||
for (int i = 0; i < verts; i++) {
|
||||
xy_data[i*2] = buffer[i].pos.x;
|
||||
xy_data[i*2+1] = buffer[i].pos.y;
|
||||
|
||||
uv_data[i*2] = buffer[i].uv.x;
|
||||
uv_data[i*2+1] = buffer[i].uv.y;
|
||||
|
||||
color_data[i].r = buffer[i].color.x;
|
||||
color_data[i].g = buffer[i].color.y;
|
||||
color_data[i].b = buffer[i].color.z;
|
||||
color_data[i].a = buffer[i].color.w;
|
||||
}
|
||||
|
||||
size_t quads = verts/4;
|
||||
size_t count = quads*6;
|
||||
|
||||
// Create indices
|
||||
uint16_t *indices = malloc(sizeof(uint16_t)*count);
|
||||
for (int i = 0, v = 0; i < count; i += 6, v += 4) {
|
||||
indices[i] = v;
|
||||
indices[i+1] = v+2;
|
||||
indices[i+2] = v+1;
|
||||
indices[i+3] = v+2;
|
||||
indices[i+4] = v+3;
|
||||
indices[i+5] = v+1;
|
||||
}
|
||||
|
||||
// Create blobs for geometry data
|
||||
JS_SetPropertyStr(js, ret, "xy", js_new_blob_stoned_copy(js, xy_data, xy_size));
|
||||
JS_SetPropertyStr(js, ret, "xy_stride", JS_NewInt32(js, 2 * sizeof(float)));
|
||||
JS_SetPropertyStr(js, ret, "uv", js_new_blob_stoned_copy(js, uv_data, uv_size));
|
||||
JS_SetPropertyStr(js, ret, "uv_stride", JS_NewInt32(js, 2 * sizeof(float)));
|
||||
JS_SetPropertyStr(js, ret, "color", js_new_blob_stoned_copy(js, color_data, color_size));
|
||||
JS_SetPropertyStr(js, ret, "color_stride", JS_NewInt32(js, sizeof(SDL_FColor)));
|
||||
JS_SetPropertyStr(js, ret, "indices", js_new_blob_stoned_copy(js, indices, sizeof(uint16_t)*count));
|
||||
JS_SetPropertyStr(js, ret, "num_vertices", JS_NewInt32(js, verts));
|
||||
JS_SetPropertyStr(js, ret, "num_indices", JS_NewInt32(js, count));
|
||||
JS_SetPropertyStr(js, ret, "size_indices", JS_NewInt32(js, 2)); // uint16_t size
|
||||
|
||||
free(xy_data);
|
||||
free(uv_data);
|
||||
free(color_data);
|
||||
free(indices);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
typedef struct lrtb lrtb;
|
||||
|
||||
@@ -280,8 +207,6 @@ char *js2strdup(JSContext *js, JSValue v) {
|
||||
|
||||
#include "qjs_macros.h"
|
||||
|
||||
QJSCLASS(datastream,)
|
||||
|
||||
JSValue angle2js(JSContext *js,double g) {
|
||||
return number2js(js,g*HMM_RadToTurn);
|
||||
}
|
||||
@@ -658,185 +583,6 @@ static const JSCFunctionListEntry js_console_funcs[] = {
|
||||
MIST_FUNC_DEF(console,print,1),
|
||||
};
|
||||
|
||||
JSC_CCALL(datastream_time, return number2js(js,plm_get_time(js2datastream(js,self)->plm)); )
|
||||
JSC_CCALL(datastream_seek, ds_seek(js2datastream(js,self), js2number(js,argv[0])))
|
||||
JSC_CCALL(datastream_advance, ds_advance(js2datastream(js,self), js2number(js,argv[0])))
|
||||
JSC_CCALL(datastream_duration, return number2js(js,ds_length(js2datastream(js,self))))
|
||||
JSC_CCALL(datastream_framerate, return number2js(js,plm_get_framerate(js2datastream(js,self)->plm)))
|
||||
|
||||
JSC_GETSET_CALLBACK(datastream, callback)
|
||||
|
||||
static const JSCFunctionListEntry js_datastream_funcs[] = {
|
||||
MIST_FUNC_DEF(datastream, time, 0),
|
||||
MIST_FUNC_DEF(datastream, seek, 1),
|
||||
MIST_FUNC_DEF(datastream, advance, 1),
|
||||
MIST_FUNC_DEF(datastream, duration, 0),
|
||||
MIST_FUNC_DEF(datastream, framerate, 0),
|
||||
CGETSET_ADD(datastream, callback),
|
||||
};
|
||||
|
||||
// input: (encoded image data of jpg, png, bmp, tiff)
|
||||
JSC_CCALL(os_image_decode,
|
||||
size_t len;
|
||||
void *raw = js_get_blob_data(js, &len, argv[0]);
|
||||
if (!raw) return JS_ThrowReferenceError(js, "could not load texture with array buffer");
|
||||
|
||||
int n, width, height;
|
||||
void *data = stbi_load_from_memory(raw, len, &width, &height, &n, 4);
|
||||
|
||||
if (!data)
|
||||
return JS_ThrowReferenceError(js, "no known image type from pixel data: %s", stbi_failure_reason());
|
||||
|
||||
if (width <= 0 || height <= 0) {
|
||||
free(data);
|
||||
return JS_ThrowReferenceError(js, "decoded image has invalid size: %dx%d", width, height);
|
||||
}
|
||||
|
||||
int pitch = width*4;
|
||||
size_t pixels_size = pitch * height;
|
||||
|
||||
// Create JS object with surface data
|
||||
JSValue obj = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, obj, "width", JS_NewInt32(js, width));
|
||||
JS_SetPropertyStr(js, obj, "height", JS_NewInt32(js, height));
|
||||
JS_SetPropertyStr(js, obj, "format", JS_NewString(js, "rgba32"));
|
||||
JS_SetPropertyStr(js, obj, "pitch", JS_NewInt32(js, pitch));
|
||||
JS_SetPropertyStr(js, obj, "pixels", js_new_blob_stoned_copy(js, data, pixels_size));
|
||||
JS_SetPropertyStr(js, obj, "depth", JS_NewInt32(js, 8));
|
||||
JS_SetPropertyStr(js, obj, "hdr", JS_NewBool(js,0));
|
||||
|
||||
free(data);
|
||||
ret = obj;
|
||||
)
|
||||
|
||||
// input: (gif image data)
|
||||
JSC_CCALL(os_make_gif,
|
||||
size_t rawlen;
|
||||
void *raw = js_get_blob_data(js, &rawlen, argv[0]);
|
||||
if (!raw) return JS_ThrowReferenceError(js, "could not load gif from supplied array buffer");
|
||||
|
||||
int n;
|
||||
int frames;
|
||||
int *delays;
|
||||
int width;
|
||||
int height;
|
||||
void *pixels = stbi_load_gif_from_memory(raw, rawlen, &delays, &width, &height, &frames, &n, 4);
|
||||
|
||||
if (!pixels) {
|
||||
return JS_ThrowReferenceError(js, "1decode GIF: %s", stbi_failure_reason());
|
||||
}
|
||||
|
||||
// Always return an array of surfaces, even for single frame
|
||||
JSValue surface_array = JS_NewArray(js);
|
||||
ret = surface_array;
|
||||
|
||||
for (int i = 0; i < frames; i++) {
|
||||
// Create surface data object
|
||||
JSValue surfData = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, surfData, "width", JS_NewInt32(js, width));
|
||||
JS_SetPropertyStr(js, surfData, "height", JS_NewInt32(js, height));
|
||||
JS_SetPropertyStr(js, surfData, "format", JS_NewString(js, "rgba32"));
|
||||
JS_SetPropertyStr(js, surfData, "pitch", JS_NewInt32(js, width*4));
|
||||
|
||||
void *frame_pixels = (unsigned char*)pixels+(width*height*4*i);
|
||||
JS_SetPropertyStr(js, surfData, "pixels", js_new_blob_stoned_copy(js, frame_pixels, width*height*4));
|
||||
|
||||
// Add time property for animation frames
|
||||
if (frames > 1 && delays) {
|
||||
JS_SetPropertyStr(js, surfData, "time", number2js(js,(float)delays[i]/1000.0));
|
||||
}
|
||||
|
||||
JS_SetPropertyUint32(js, surface_array, i, surfData);
|
||||
}
|
||||
|
||||
CLEANUP:
|
||||
if (delays) free(delays);
|
||||
if (pixels) free(pixels);
|
||||
)
|
||||
|
||||
JSValue aseframe2js(JSContext *js, ase_frame_t aframe)
|
||||
{
|
||||
JSValue frame = JS_NewObject(js);
|
||||
|
||||
// Create surface data object instead of SDL_Surface
|
||||
JSValue surfData = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, surfData, "width", JS_NewInt32(js, aframe.ase->w));
|
||||
JS_SetPropertyStr(js, surfData, "height", JS_NewInt32(js, aframe.ase->h));
|
||||
JS_SetPropertyStr(js, surfData, "format", JS_NewString(js, "rgba32"));
|
||||
JS_SetPropertyStr(js, surfData, "pitch", JS_NewInt32(js, aframe.ase->w*4));
|
||||
JS_SetPropertyStr(js, surfData, "pixels", js_new_blob_stoned_copy(js, aframe.pixels, aframe.ase->w*aframe.ase->h*4));
|
||||
|
||||
JS_SetPropertyStr(js, frame, "surface", surfData);
|
||||
JS_SetPropertyStr(js, frame, "time", number2js(js,(float)aframe.duration_milliseconds/1000.0));
|
||||
return frame;
|
||||
}
|
||||
|
||||
// input: (aseprite data)
|
||||
JSC_CCALL(os_make_aseprite,
|
||||
size_t rawlen;
|
||||
void *raw = js_get_blob_data(js,&rawlen,argv[0]);
|
||||
|
||||
ase_t *ase = cute_aseprite_load_from_memory(raw, rawlen, NULL);
|
||||
|
||||
if (!ase)
|
||||
return JS_ThrowReferenceError(js, "could not load aseprite from supplied array buffer: %s", aseprite_GetError());
|
||||
|
||||
if (ase->tag_count == 0) {
|
||||
// we're dealing with a single frame image, or single animation
|
||||
if (ase->frame_count == 1) {
|
||||
JSValue obj = aseframe2js(js,ase->frames[0]);
|
||||
cute_aseprite_free(ase);
|
||||
return obj;
|
||||
} else {
|
||||
// Multiple frames but no tags - create a simple animation
|
||||
JSValue obj = JS_NewObject(js);
|
||||
JSValue frames = JS_NewArray(js);
|
||||
for (int f = 0; f < ase->frame_count; f++) {
|
||||
JSValue frame = aseframe2js(js,ase->frames[f]);
|
||||
JS_SetPropertyUint32(js, frames, f, frame);
|
||||
}
|
||||
JS_SetPropertyStr(js, obj, "frames", frames);
|
||||
JS_SetPropertyStr(js, obj, "loop", JS_NewBool(js, true));
|
||||
ret = obj;
|
||||
cute_aseprite_free(ase);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
JSValue obj = JS_NewObject(js);
|
||||
|
||||
for (int t = 0; t < ase->tag_count; t++) {
|
||||
ase_tag_t tag = ase->tags[t];
|
||||
JSValue anim = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, anim, "repeat", number2js(js,tag.repeat));
|
||||
switch(tag.loop_animation_direction) {
|
||||
case ASE_ANIMATION_DIRECTION_FORWARDS:
|
||||
JS_SetPropertyStr(js, anim, "loop", JS_NewString(js,"forward"));
|
||||
break;
|
||||
case ASE_ANIMATION_DIRECTION_BACKWORDS:
|
||||
JS_SetPropertyStr(js, anim, "loop", JS_NewString(js,"backward"));
|
||||
break;
|
||||
case ASE_ANIMATION_DIRECTION_PINGPONG:
|
||||
JS_SetPropertyStr(js, anim, "loop", JS_NewString(js,"pingpong"));
|
||||
break;
|
||||
}
|
||||
|
||||
int _frame = 0;
|
||||
JSValue frames = JS_NewArray(js);
|
||||
for (int f = tag.from_frame; f <= tag.to_frame; f++) {
|
||||
JSValue frame = aseframe2js(js,ase->frames[f]);
|
||||
JS_SetPropertyUint32(js, frames, _frame, frame);
|
||||
_frame++;
|
||||
}
|
||||
JS_SetPropertyStr(js, anim, "frames", frames);
|
||||
JS_SetPropertyStr(js, obj, tag.name, anim);
|
||||
}
|
||||
|
||||
ret = obj;
|
||||
|
||||
cute_aseprite_free(ase);
|
||||
)
|
||||
|
||||
|
||||
JSC_SCALL(os_system, ret = number2js(js,system(str)); )
|
||||
|
||||
@@ -898,71 +644,6 @@ JSC_CCALL(os_make_line_prim,
|
||||
*/
|
||||
)
|
||||
|
||||
static void render_frame(plm_t *mpeg, plm_frame_t *frame, datastream *ds) {
|
||||
if (JS_IsNull(ds->callback)) return;
|
||||
uint8_t *rgb = malloc(frame->height*frame->width*4);
|
||||
memset(rgb,255,frame->height*frame->width*4);
|
||||
plm_frame_to_rgba(frame, rgb, frame->width*4);
|
||||
|
||||
// Create surface data object instead of SDL_Surface
|
||||
JSValue surfData = JS_NewObject(ds->js);
|
||||
JS_SetPropertyStr(ds->js, surfData, "width", JS_NewInt32(ds->js, frame->width));
|
||||
JS_SetPropertyStr(ds->js, surfData, "height", JS_NewInt32(ds->js, frame->height));
|
||||
JS_SetPropertyStr(ds->js, surfData, "format", JS_NewString(ds->js, "rgba32"));
|
||||
JS_SetPropertyStr(ds->js, surfData, "pitch", JS_NewInt32(ds->js, frame->width*4));
|
||||
JS_SetPropertyStr(ds->js, surfData, "pixels", js_new_blob_stoned_copy(ds->js, rgb, frame->height*frame->width*4));
|
||||
|
||||
JSValue s[1];
|
||||
s[0] = surfData;
|
||||
JSValue cb = JS_DupValue(ds->js,ds->callback);
|
||||
JSValue ret = JS_Call(ds->js, cb, JS_NULL, 1, s);
|
||||
JS_FreeValue(ds->js,cb);
|
||||
free(rgb);
|
||||
uncaught_exception(ds->js,ret);
|
||||
}
|
||||
|
||||
JSC_CCALL(os_make_video,
|
||||
size_t len;
|
||||
void *data = js_get_blob_data(js,&len,argv[0]);
|
||||
datastream *ds = ds_openvideo(data, len);
|
||||
if (!ds) return JS_ThrowReferenceError(js, "Video file was not valid.");
|
||||
ds->js = js;
|
||||
ds->callback = JS_NULL;
|
||||
plm_set_video_decode_callback(ds->plm, render_frame, ds);
|
||||
return datastream2js(js,ds);
|
||||
)
|
||||
|
||||
JSC_CCALL(os_rectpack,
|
||||
int width = js2number(js,argv[0]);
|
||||
int height = js2number(js,argv[1]);
|
||||
int num = JS_ArrayLength(js,argv[2]);
|
||||
stbrp_context ctx[1];
|
||||
stbrp_rect rects[num];
|
||||
|
||||
for (int i = 0; i < num; i++) {
|
||||
HMM_Vec2 wh = js2vec2(js,js_getpropertyuint32(js, argv[2], i));
|
||||
rects[i].w = wh.x;
|
||||
rects[i].h = wh.y;
|
||||
rects[i].id = i;
|
||||
}
|
||||
|
||||
stbrp_node nodes[width];
|
||||
stbrp_init_target(ctx, width, height, nodes, width);
|
||||
int packed = stbrp_pack_rects(ctx, rects, num);
|
||||
|
||||
if (!packed) {
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
ret = JS_NewArray(js);
|
||||
for (int i = 0; i < num; i++) {
|
||||
HMM_Vec2 pos;
|
||||
pos.x = rects[i].x;
|
||||
pos.y = rects[i].y;
|
||||
JS_SetPropertyUint32(js, ret, i, vec22js(js,pos));
|
||||
}
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_util_funcs[] = {
|
||||
MIST_FUNC_DEF(os, guid, 0),
|
||||
};
|
||||
@@ -987,19 +668,6 @@ JSC_CCALL(graphics_hsl_to_rgb,
|
||||
return color2js(js, (colorf){r+m, g+m, b+m, 1});
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_graphics_funcs[] = {
|
||||
MIST_FUNC_DEF(os, rectpack, 3),
|
||||
MIST_FUNC_DEF(os, image_decode, 1),
|
||||
MIST_FUNC_DEF(os, make_gif, 1),
|
||||
MIST_FUNC_DEF(os, make_aseprite, 1),
|
||||
MIST_FUNC_DEF(os, make_line_prim, 5),
|
||||
MIST_FUNC_DEF(graphics, hsl_to_rgb, 3),
|
||||
};
|
||||
|
||||
static const JSCFunctionListEntry js_video_funcs[] = {
|
||||
MIST_FUNC_DEF(os, make_video, 1),
|
||||
};
|
||||
|
||||
static void *get_main_module_handle() {
|
||||
#if defined(_WIN32)
|
||||
return GetModuleHandle(NULL);
|
||||
@@ -1100,23 +768,12 @@ JSC_SCALL(os_load_internal,
|
||||
ret = js_use(js);
|
||||
)
|
||||
|
||||
JSValue js_graphics_use(JSContext *js) {
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js,mod,js_graphics_funcs,countof(js_graphics_funcs));
|
||||
return mod;
|
||||
}
|
||||
|
||||
JSValue js_util_use(JSContext *js) {
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js,mod,js_util_funcs,countof(js_util_funcs));
|
||||
return mod;
|
||||
}
|
||||
|
||||
JSValue js_video_use(JSContext *js) {
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js,mod,js_video_funcs,countof(js_video_funcs));
|
||||
return mod;
|
||||
}
|
||||
|
||||
JSValue js_console_use(JSContext *js) {
|
||||
JSValue mod = JS_NewObject(js);
|
||||
|
||||
@@ -71,7 +71,6 @@ lrtb js2lrtb(JSContext *js, JSValue v);
|
||||
int js2bool(JSContext *js, JSValue v);
|
||||
JSValue make_gpu_buffer(JSContext *js, void *data, size_t size, int type, int elements, int copy, int index);
|
||||
JSValue make_quad_indices_buffer(JSContext *js, int quads);
|
||||
JSValue quads_to_mesh(JSContext *js, text_vert *buffer);
|
||||
|
||||
// SDL type conversion functions
|
||||
SDL_Window *js2SDL_Window(JSContext *js, JSValue v);
|
||||
|
||||
1196
source/layout.h
1196
source/layout.h
File diff suppressed because it is too large
Load Diff
189
source/model.c
189
source/model.c
@@ -1,189 +0,0 @@
|
||||
#include "model.h"
|
||||
|
||||
#include "stb_ds.h"
|
||||
|
||||
#include "render.h"
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
|
||||
#include "math.h"
|
||||
#include "time.h"
|
||||
|
||||
#include <cgltf.h>
|
||||
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "jsffi.h"
|
||||
|
||||
SDL_GPUBuffer *texcoord_floats(float *f, int n)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *float_buffer(float *f, int v)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *index_buffer(float *f, int verts)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
uint32_t pack_int10_n2(float *norm)
|
||||
{
|
||||
uint32_t ret = 0;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int n = (norm[i]+1.0)*511;
|
||||
ret |= (n & 0x3ff) << (10*i);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Pack an array of normals into
|
||||
SDL_GPUBuffer *normal_floats(float *f, int n)
|
||||
{
|
||||
return float_buffer(f, n);
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *ubyten_buffer(float *f, int v)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *ubyte_buffer(float *f, int v)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *accessor2buffer(cgltf_accessor *a, int type)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void packFloats(float *src, float *dest, int srcLength) {
|
||||
int i, j;
|
||||
for (i = 0, j = 0; i < srcLength; i += 3, j += 4) {
|
||||
dest[j] = src[i];
|
||||
dest[j + 1] = src[i + 1];
|
||||
dest[j + 2] = src[i + 2];
|
||||
dest[j + 3] = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
static md5joint *node2joint(skin *sk, cgltf_node *n, cgltf_skin *skin)
|
||||
{
|
||||
int k = 0;
|
||||
while (skin->joints[k] != n && k < skin->joints_count) k++;
|
||||
return sk->joints+k;
|
||||
}
|
||||
|
||||
animation *gltf_anim(cgltf_animation *anim, skin *sk, cgltf_skin *skin)
|
||||
{
|
||||
animation *ret = calloc(sizeof(*ret), 1);
|
||||
animation an = *ret;
|
||||
arrsetlen(an.samplers, anim->samplers_count);
|
||||
|
||||
for (int i = 0; i < anim->samplers_count; i++) {
|
||||
cgltf_animation_sampler s = anim->samplers[i];
|
||||
sampler samp = (sampler){0};
|
||||
int n = cgltf_accessor_unpack_floats(s.input, NULL, 0);
|
||||
arrsetlen(samp.times, n);
|
||||
cgltf_accessor_unpack_floats(s.input, samp.times, n);
|
||||
|
||||
n = cgltf_accessor_unpack_floats(s.output, NULL, 0);
|
||||
int comp = cgltf_num_components(s.output->type);
|
||||
arrsetlen(samp.data, n/comp);
|
||||
if (comp == 4)
|
||||
cgltf_accessor_unpack_floats(s.output, samp.data, n);
|
||||
else {
|
||||
float *out = malloc(sizeof(*out)*n);
|
||||
cgltf_accessor_unpack_floats(s.output, out, n);
|
||||
packFloats(out, samp.data, n);
|
||||
free(out);
|
||||
}
|
||||
|
||||
samp.type = s.interpolation;
|
||||
|
||||
if (samp.type == LINEAR && comp == 4)
|
||||
samp.type = SLERP;
|
||||
|
||||
an.samplers[i] = samp;
|
||||
}
|
||||
|
||||
for (int i = 0; i < anim->channels_count; i++) {
|
||||
cgltf_animation_channel ch = anim->channels[i];
|
||||
struct anim_channel ach = (struct anim_channel){0};
|
||||
md5joint *md = node2joint(sk, ch.target_node, skin);
|
||||
switch(ch.target_path) {
|
||||
case cgltf_animation_path_type_translation:
|
||||
ach.target = &md->pos;
|
||||
break;
|
||||
case cgltf_animation_path_type_rotation:
|
||||
ach.target = &md->rot;
|
||||
break;
|
||||
case cgltf_animation_path_type_scale:
|
||||
ach.target = &md->scale;
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
ach.sampler = an.samplers+(ch.sampler-anim->samplers);
|
||||
|
||||
arrput(an.channels, ach);
|
||||
}
|
||||
|
||||
an.time = 0;
|
||||
|
||||
*ret = an;
|
||||
return ret;
|
||||
}
|
||||
|
||||
skin *make_gltf_skin(cgltf_skin *skin, cgltf_data *data)
|
||||
{
|
||||
int n = cgltf_accessor_unpack_floats(skin->inverse_bind_matrices, NULL, 0);
|
||||
struct skin *sk = NULL;
|
||||
sk = calloc(sizeof(*sk),1);
|
||||
arrsetlen(sk->invbind, n/16);
|
||||
cgltf_accessor_unpack_floats(skin->inverse_bind_matrices, sk->invbind, n);
|
||||
|
||||
arrsetlen(sk->joints, skin->joints_count);
|
||||
|
||||
for (int i = 0; i < 50; i++)
|
||||
sk->binds[i] = MAT1;
|
||||
|
||||
for (int i = 0; i < skin->joints_count; i++) {
|
||||
cgltf_node *n = skin->joints[i];
|
||||
md5joint *j = sk->joints+i;
|
||||
|
||||
if (n == skin->skeleton)
|
||||
j->parent = NULL;
|
||||
else
|
||||
j->parent = node2joint(sk, n->parent, skin);
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
j->pos.e[i] = n->translation[i];
|
||||
j->scale.e[i] = n->scale[i];
|
||||
}
|
||||
for (int i = 0; i < 4; i++)
|
||||
j->rot.e[i] = n->rotation[i];
|
||||
}
|
||||
|
||||
sk->anim = gltf_anim(data->animations+0, sk, skin);
|
||||
|
||||
return sk;
|
||||
}
|
||||
|
||||
void skin_calculate(skin *sk)
|
||||
{
|
||||
// animation_run(sk->anim, apptime());
|
||||
for (int i = 0; i < arrlen(sk->joints); i++) {
|
||||
md5joint *md = sk->joints+i;
|
||||
md->t = HMM_M4TRS(md->pos.xyz, md->rot, md->scale.xyz);
|
||||
if (md->parent)
|
||||
md->t = HMM_MulM4(md->parent->t, md->t);
|
||||
|
||||
sk->binds[i] = HMM_MulM4(md->t, sk->invbind[i]);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
#ifndef MODEL_H
|
||||
#define MODEL_H
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
#include "transform.h"
|
||||
#include "anim.h"
|
||||
#include "cgltf.h"
|
||||
|
||||
#define MAT_POS 0
|
||||
#define MAT_UV 1
|
||||
#define MAT_NORM 2
|
||||
#define MAT_BONE 3
|
||||
#define MAT_WEIGHT 4
|
||||
#define MAT_COLOR 5
|
||||
#define MAT_TAN 6
|
||||
#define MAT_ANGLE 7
|
||||
#define MAT_WH 8
|
||||
#define MAT_ST 9
|
||||
#define MAT_PPOS 10
|
||||
#define MAT_SCALE 11
|
||||
#define MAT_INDEX 100
|
||||
|
||||
typedef struct md5joint {
|
||||
struct md5joint *parent;
|
||||
HMM_Vec4 pos;
|
||||
HMM_Quat rot;
|
||||
HMM_Vec4 scale;
|
||||
HMM_Mat4 t;
|
||||
} md5joint;
|
||||
|
||||
typedef struct skin {
|
||||
md5joint *joints;
|
||||
HMM_Mat4 *invbind;
|
||||
HMM_Mat4 binds[50]; /* binds = joint * invbind */
|
||||
animation *anim;
|
||||
} skin;
|
||||
|
||||
//sg_buffer accessor2buffer(cgltf_accessor *a, int type);
|
||||
skin *make_gltf_skin(cgltf_skin *skin, cgltf_data *data);
|
||||
void skin_calculate(skin *sk);
|
||||
|
||||
/*sg_buffer float_buffer(float *f, int v);
|
||||
sg_buffer index_buffer(float *f, int verts);
|
||||
sg_buffer texcoord_floats(float *f, int n);
|
||||
sg_buffer par_idx_buffer(uint32_t *i, int v);
|
||||
sg_buffer normal_floats(float *f, int n);
|
||||
sg_buffer ubyten_buffer(float *f, int v);
|
||||
sg_buffer ubyte_buffer(float *f, int v);
|
||||
sg_buffer joint_buf(float *f, int v);
|
||||
sg_buffer weight_buf(float *f, int v);
|
||||
*/
|
||||
#endif
|
||||
717
source/msf_gif.h
717
source/msf_gif.h
@@ -1,717 +0,0 @@
|
||||
/*
|
||||
HOW TO USE:
|
||||
|
||||
In exactly one translation unit (.c or .cpp file), #define MSF_GIF_IMPL before including the header, like so:
|
||||
|
||||
#define MSF_GIF_IMPL
|
||||
#include "msf_gif.h"
|
||||
|
||||
Everywhere else, just include the header like normal.
|
||||
|
||||
|
||||
USAGE EXAMPLE:
|
||||
|
||||
int width = 480, height = 320, centisecondsPerFrame = 5, bitDepth = 16;
|
||||
MsfGifState gifState = {};
|
||||
// msf_gif_bgra_flag = true; //optionally, set this flag if your pixels are in BGRA format instead of RGBA
|
||||
// msf_gif_alpha_threshold = 128; //optionally, enable transparency (see function documentation below for details)
|
||||
msf_gif_begin(&gifState, width, height);
|
||||
msf_gif_frame(&gifState, ..., centisecondsPerFrame, bitDepth, width * 4); //frame 1
|
||||
msf_gif_frame(&gifState, ..., centisecondsPerFrame, bitDepth, width * 4); //frame 2
|
||||
msf_gif_frame(&gifState, ..., centisecondsPerFrame, bitDepth, width * 4); //frame 3, etc...
|
||||
MsfGifResult result = msf_gif_end(&gifState);
|
||||
if (result.data) {
|
||||
FILE * fp = fopen("MyGif.gif", "wb");
|
||||
fwrite(result.data, result.dataSize, 1, fp);
|
||||
fclose(fp);
|
||||
}
|
||||
msf_gif_free(result);
|
||||
|
||||
Detailed function documentation can be found in the header section below.
|
||||
|
||||
|
||||
ERROR HANDLING:
|
||||
|
||||
If memory allocation fails, the functions will signal the error via their return values.
|
||||
If one function call fails, the library will free all of its allocations,
|
||||
and all subsequent calls will safely no-op and return 0 until the next call to `msf_gif_begin()`.
|
||||
Therefore, it's safe to check only the return value of `msf_gif_end()`.
|
||||
|
||||
|
||||
REPLACING MALLOC:
|
||||
|
||||
This library uses malloc+realloc+free internally for memory allocation.
|
||||
To facilitate integration with custom memory allocators, these calls go through macros, which can be redefined.
|
||||
The expected function signature equivalents of the macros are as follows:
|
||||
|
||||
void * MSF_GIF_MALLOC(void * context, size_t newSize)
|
||||
void * MSF_GIF_REALLOC(void * context, void * oldMemory, size_t oldSize, size_t newSize)
|
||||
void MSF_GIF_FREE(void * context, void * oldMemory, size_t oldSize)
|
||||
|
||||
If your allocator needs a context pointer, you can set the `customAllocatorContext` field of the MsfGifState struct
|
||||
before calling msf_gif_begin(), and it will be passed to all subsequent allocator macro calls.
|
||||
|
||||
The maximum number of bytes the library will allocate to encode a single gif is bounded by the following formula:
|
||||
`(2 * 1024 * 1024) + (width * height * 8) + ((1024 + width * height * 1.5) * 3 * frameCount)`
|
||||
The peak heap memory usage in bytes, if using a general-purpose heap allocator, is bounded by the following formula:
|
||||
`(2 * 1024 * 1024) + (width * height * 9.5) + 1024 + (16 * frameCount) + (2 * sizeOfResultingGif)
|
||||
|
||||
|
||||
See end of file for license information.
|
||||
*/
|
||||
|
||||
//version 2.2
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// HEADER ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef MSF_GIF_H
|
||||
#define MSF_GIF_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct {
|
||||
void * data;
|
||||
size_t dataSize;
|
||||
|
||||
size_t allocSize; //internal use
|
||||
void * contextPointer; //internal use
|
||||
} MsfGifResult;
|
||||
|
||||
typedef struct { //internal use
|
||||
uint32_t * pixels;
|
||||
int depth, count, rbits, gbits, bbits;
|
||||
} MsfCookedFrame;
|
||||
|
||||
typedef struct MsfGifBuffer {
|
||||
struct MsfGifBuffer * next;
|
||||
size_t size;
|
||||
uint8_t data[1];
|
||||
} MsfGifBuffer;
|
||||
|
||||
typedef size_t (* MsfGifFileWriteFunc) (const void * buffer, size_t size, size_t count, void * stream);
|
||||
typedef struct {
|
||||
MsfGifFileWriteFunc fileWriteFunc;
|
||||
void * fileWriteData;
|
||||
MsfCookedFrame previousFrame;
|
||||
MsfCookedFrame currentFrame;
|
||||
int16_t * lzwMem;
|
||||
MsfGifBuffer * listHead;
|
||||
MsfGifBuffer * listTail;
|
||||
int width, height;
|
||||
void * customAllocatorContext;
|
||||
int framesSubmitted; //needed for transparency to work correctly (because we reach into the previous frame)
|
||||
} MsfGifState;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif //__cplusplus
|
||||
|
||||
/**
|
||||
* @param width Image width in pixels.
|
||||
* @param height Image height in pixels.
|
||||
* @return Non-zero on success, 0 on error.
|
||||
*/
|
||||
int msf_gif_begin(MsfGifState * handle, int width, int height);
|
||||
|
||||
/**
|
||||
* @param pixelData Pointer to raw framebuffer data. Rows must be contiguous in memory, in RGBA8 format
|
||||
* (or BGRA8 if you have set `msf_gif_bgra_flag = true`).
|
||||
* Note: This function does NOT free `pixelData`. You must free it yourself afterwards.
|
||||
* @param centiSecondsPerFrame How many hundredths of a second this frame should be displayed for.
|
||||
* Note: This being specified in centiseconds is a limitation of the GIF format.
|
||||
* @param maxBitDepth Limits how many bits per pixel can be used when quantizing the gif.
|
||||
* The actual bit depth chosen for a given frame will be less than or equal to
|
||||
* the supplied maximum, depending on the variety of colors used in the frame.
|
||||
* `maxBitDepth` will be clamped between 1 and 16. The recommended default is 16.
|
||||
* Lowering this value can result in faster exports and smaller gifs,
|
||||
* but the quality may suffer.
|
||||
* Please experiment with this value to find what works best for your application.
|
||||
* @param pitchInBytes The number of bytes from the beginning of one row of pixels to the beginning of the next.
|
||||
* If you want to flip the image, just pass in a negative pitch.
|
||||
* @return Non-zero on success, 0 on error.
|
||||
*/
|
||||
int msf_gif_frame(MsfGifState * handle, uint8_t * pixelData, int centiSecondsPerFame, int maxBitDepth, int pitchInBytes);
|
||||
|
||||
/**
|
||||
* @return A block of memory containing the gif file data, or NULL on error.
|
||||
* You are responsible for freeing this via `msf_gif_free()`.
|
||||
*/
|
||||
MsfGifResult msf_gif_end(MsfGifState * handle);
|
||||
|
||||
/**
|
||||
* @param result The MsfGifResult struct, verbatim as it was returned from `msf_gif_end()`.
|
||||
*/
|
||||
void msf_gif_free(MsfGifResult result);
|
||||
|
||||
//The gif format only supports 1-bit transparency, meaning a pixel will either be fully transparent or fully opaque.
|
||||
//Pixels with an alpha value less than the alpha threshold will be treated as transparent.
|
||||
//To enable exporting transparent gifs, set it to a value between 1 and 255 (inclusive) before calling msf_gif_frame().
|
||||
//Setting it to 0 causes the alpha channel to be ignored. Its initial value is 0.
|
||||
extern int msf_gif_alpha_threshold;
|
||||
|
||||
//Set `msf_gif_bgra_flag = true` before calling `msf_gif_frame()` if your pixels are in BGRA byte order instead of RBGA.
|
||||
extern int msf_gif_bgra_flag;
|
||||
|
||||
|
||||
|
||||
//TO-FILE FUNCTIONS
|
||||
//These functions are equivalent to the ones above, but they write results to a file incrementally,
|
||||
//instead of building a buffer in memory. This can result in lower memory usage when saving large gifs,
|
||||
//because memory usage is bounded by only the size of a single frame, and is not dependent on the number of frames.
|
||||
//There is currently no reason to use these unless you are on a memory-constrained platform.
|
||||
//If in doubt about which API to use, for now you should use the normal (non-file) functions above.
|
||||
//The signature of MsfGifFileWriteFunc matches fwrite for convenience, so that you can use the C file API like so:
|
||||
// FILE * fp = fopen("MyGif.gif", "wb");
|
||||
// msf_gif_begin_to_file(&handle, width, height, (MsfGifFileWriteFunc) fwrite, (void *) fp);
|
||||
// msf_gif_frame_to_file(...)
|
||||
// msf_gif_end_to_file(&handle);
|
||||
// fclose(fp);
|
||||
//If you use a custom file write function, you must take care to return the same values that fwrite() would return.
|
||||
//Note that all three functions will potentially write to the file.
|
||||
int msf_gif_begin_to_file(MsfGifState * handle, int width, int height, MsfGifFileWriteFunc func, void * filePointer);
|
||||
int msf_gif_frame_to_file(MsfGifState * handle, uint8_t * pixelData, int centiSecondsPerFame, int maxBitDepth, int pitchInBytes);
|
||||
int msf_gif_end_to_file(MsfGifState * handle); //returns 0 on error and non-zero on success
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif //__cplusplus
|
||||
|
||||
#endif //MSF_GIF_H
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// IMPLEMENTATION ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifdef MSF_GIF_IMPL
|
||||
#ifndef MSF_GIF_ALREADY_IMPLEMENTED_IN_THIS_TRANSLATION_UNIT
|
||||
#define MSF_GIF_ALREADY_IMPLEMENTED_IN_THIS_TRANSLATION_UNIT
|
||||
|
||||
//ensure the library user has either defined all of malloc/realloc/free, or none
|
||||
#if defined(MSF_GIF_MALLOC) && defined(MSF_GIF_REALLOC) && defined(MSF_GIF_FREE) //ok
|
||||
#elif !defined(MSF_GIF_MALLOC) && !defined(MSF_GIF_REALLOC) && !defined(MSF_GIF_FREE) //ok
|
||||
#else
|
||||
#error "You must either define all of MSF_GIF_MALLOC, MSF_GIF_REALLOC, and MSF_GIF_FREE, or define none of them"
|
||||
#endif
|
||||
|
||||
//provide default allocator definitions that redirect to the standard global allocator
|
||||
#if !defined(MSF_GIF_MALLOC)
|
||||
#include <stdlib.h> //malloc, etc.
|
||||
#define MSF_GIF_MALLOC(contextPointer, newSize) malloc(newSize)
|
||||
#define MSF_GIF_REALLOC(contextPointer, oldMemory, oldSize, newSize) realloc(oldMemory, newSize)
|
||||
#define MSF_GIF_FREE(contextPointer, oldMemory, oldSize) free(oldMemory)
|
||||
#endif
|
||||
|
||||
//instrumentation for capturing profiling traces (useless for the library user, but useful for the library author)
|
||||
#ifdef MSF_GIF_ENABLE_TRACING
|
||||
#define MsfTimeFunc TimeFunc
|
||||
#define MsfTimeLoop TimeLoop
|
||||
#define msf_init_profiling_thread init_profiling_thread
|
||||
#else
|
||||
#define MsfTimeFunc
|
||||
#define MsfTimeLoop(name)
|
||||
#define msf_init_profiling_thread()
|
||||
#endif //MSF_GIF_ENABLE_TRACING
|
||||
|
||||
#include <string.h> //memcpy
|
||||
|
||||
//TODO: use compiler-specific notation to force-inline functions currently marked inline
|
||||
#if defined(__GNUC__) //gcc, clang
|
||||
static inline int msf_bit_log(int i) { return 32 - __builtin_clz(i); }
|
||||
#elif defined(_MSC_VER) //msvc
|
||||
#include <intrin.h>
|
||||
static inline int msf_bit_log(int i) { unsigned long idx; _BitScanReverse(&idx, i); return idx + 1; }
|
||||
#else //fallback implementation for other compilers
|
||||
//from https://stackoverflow.com/a/31718095/3064745 - thanks!
|
||||
static inline int msf_bit_log(int i) {
|
||||
static const int MultiplyDeBruijnBitPosition[32] = {
|
||||
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
|
||||
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31,
|
||||
};
|
||||
i |= i >> 1;
|
||||
i |= i >> 2;
|
||||
i |= i >> 4;
|
||||
i |= i >> 8;
|
||||
i |= i >> 16;
|
||||
return MultiplyDeBruijnBitPosition[(uint32_t)(i * 0x07C4ACDDU) >> 27] + 1;
|
||||
}
|
||||
#endif
|
||||
static inline int msf_imin(int a, int b) { return a < b? a : b; }
|
||||
static inline int msf_imax(int a, int b) { return b < a? a : b; }
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// Frame Cooking ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#if (defined (__SSE2__) || defined (_M_X64) || _M_IX86_FP == 2) && !defined(MSF_GIF_NO_SSE2)
|
||||
#include <emmintrin.h>
|
||||
#endif
|
||||
|
||||
int msf_gif_alpha_threshold = 0;
|
||||
int msf_gif_bgra_flag = 0;
|
||||
|
||||
static void msf_cook_frame(MsfCookedFrame * frame, uint8_t * raw, uint8_t * used,
|
||||
int width, int height, int pitch, int depth)
|
||||
{ MsfTimeFunc
|
||||
//bit depth for each channel
|
||||
const static int rdepthsArray[17] = { 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5 };
|
||||
const static int gdepthsArray[17] = { 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6 };
|
||||
const static int bdepthsArray[17] = { 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5 };
|
||||
//this extra level of indirection looks unnecessary but we need to explicitly decay the arrays to pointers
|
||||
//in order to be able to swap them because of C's annoying not-quite-pointers, not-quite-value-types stack arrays.
|
||||
const int * rdepths = msf_gif_bgra_flag? bdepthsArray : rdepthsArray;
|
||||
const int * gdepths = gdepthsArray;
|
||||
const int * bdepths = msf_gif_bgra_flag? rdepthsArray : bdepthsArray;
|
||||
|
||||
const static int ditherKernel[16] = {
|
||||
0 << 12, 8 << 12, 2 << 12, 10 << 12,
|
||||
12 << 12, 4 << 12, 14 << 12, 6 << 12,
|
||||
3 << 12, 11 << 12, 1 << 12, 9 << 12,
|
||||
15 << 12, 7 << 12, 13 << 12, 5 << 12,
|
||||
};
|
||||
|
||||
uint32_t * cooked = frame->pixels;
|
||||
int count = 0;
|
||||
MsfTimeLoop("do") do {
|
||||
int rbits = rdepths[depth], gbits = gdepths[depth], bbits = bdepths[depth];
|
||||
int paletteSize = (1 << (rbits + gbits + bbits)) + 1;
|
||||
memset(used, 0, paletteSize * sizeof(uint8_t));
|
||||
|
||||
//TODO: document what this math does and why it's correct
|
||||
int rdiff = (1 << (8 - rbits)) - 1;
|
||||
int gdiff = (1 << (8 - gbits)) - 1;
|
||||
int bdiff = (1 << (8 - bbits)) - 1;
|
||||
short rmul = (short) ((255.0f - rdiff) / 255.0f * 257);
|
||||
short gmul = (short) ((255.0f - gdiff) / 255.0f * 257);
|
||||
short bmul = (short) ((255.0f - bdiff) / 255.0f * 257);
|
||||
|
||||
int gmask = ((1 << gbits) - 1) << rbits;
|
||||
int bmask = ((1 << bbits) - 1) << rbits << gbits;
|
||||
|
||||
MsfTimeLoop("cook") for (int y = 0; y < height; ++y) {
|
||||
int x = 0;
|
||||
|
||||
#if (defined (__SSE2__) || defined (_M_X64) || _M_IX86_FP == 2) && !defined(MSF_GIF_NO_SSE2)
|
||||
__m128i k = _mm_loadu_si128((__m128i *) &ditherKernel[(y & 3) * 4]);
|
||||
__m128i k2 = _mm_or_si128(_mm_srli_epi32(k, rbits), _mm_slli_epi32(_mm_srli_epi32(k, bbits), 16));
|
||||
for (; x < width - 3; x += 4) {
|
||||
uint8_t * pixels = &raw[y * pitch + x * 4];
|
||||
__m128i p = _mm_loadu_si128((__m128i *) pixels);
|
||||
|
||||
__m128i rb = _mm_and_si128(p, _mm_set1_epi32(0x00FF00FF));
|
||||
__m128i rb1 = _mm_mullo_epi16(rb, _mm_set_epi16(bmul, rmul, bmul, rmul, bmul, rmul, bmul, rmul));
|
||||
__m128i rb2 = _mm_adds_epu16(rb1, k2);
|
||||
__m128i r3 = _mm_srli_epi32(_mm_and_si128(rb2, _mm_set1_epi32(0x0000FFFF)), 16 - rbits);
|
||||
__m128i b3 = _mm_and_si128(_mm_srli_epi32(rb2, 32 - rbits - gbits - bbits), _mm_set1_epi32(bmask));
|
||||
|
||||
__m128i g = _mm_and_si128(_mm_srli_epi32(p, 8), _mm_set1_epi32(0x000000FF));
|
||||
__m128i g1 = _mm_mullo_epi16(g, _mm_set1_epi32(gmul));
|
||||
__m128i g2 = _mm_adds_epu16(g1, _mm_srli_epi32(k, gbits));
|
||||
__m128i g3 = _mm_and_si128(_mm_srli_epi32(g2, 16 - rbits - gbits), _mm_set1_epi32(gmask));
|
||||
|
||||
__m128i out = _mm_or_si128(_mm_or_si128(r3, g3), b3);
|
||||
|
||||
//mask in transparency based on threshold
|
||||
//NOTE: we can theoretically do a sub instead of srli by doing an unsigned compare via bias
|
||||
// to maybe save a TINY amount of throughput? but lol who cares maybe I'll do it later -m
|
||||
__m128i invAlphaMask = _mm_cmplt_epi32(_mm_srli_epi32(p, 24), _mm_set1_epi32(msf_gif_alpha_threshold));
|
||||
out = _mm_or_si128(_mm_and_si128(invAlphaMask, _mm_set1_epi32(paletteSize - 1)), _mm_andnot_si128(invAlphaMask, out));
|
||||
|
||||
//TODO: does storing this as a __m128i then reading it back as a uint32_t violate strict aliasing?
|
||||
uint32_t * c = &cooked[y * width + x];
|
||||
_mm_storeu_si128((__m128i *) c, out);
|
||||
}
|
||||
#endif
|
||||
|
||||
//scalar cleanup loop
|
||||
for (; x < width; ++x) {
|
||||
uint8_t * p = &raw[y * pitch + x * 4];
|
||||
|
||||
//transparent pixel if alpha is low
|
||||
if (p[3] < msf_gif_alpha_threshold) {
|
||||
cooked[y * width + x] = paletteSize - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
int dx = x & 3, dy = y & 3;
|
||||
int k = ditherKernel[dy * 4 + dx];
|
||||
cooked[y * width + x] =
|
||||
(msf_imin(65535, p[2] * bmul + (k >> bbits)) >> (16 - rbits - gbits - bbits) & bmask) |
|
||||
(msf_imin(65535, p[1] * gmul + (k >> gbits)) >> (16 - rbits - gbits ) & gmask) |
|
||||
msf_imin(65535, p[0] * rmul + (k >> rbits)) >> (16 - rbits );
|
||||
}
|
||||
}
|
||||
|
||||
count = 0;
|
||||
MsfTimeLoop("mark") for (int i = 0; i < width * height; ++i) {
|
||||
used[cooked[i]] = 1;
|
||||
}
|
||||
|
||||
//count used colors, transparent is ignored
|
||||
MsfTimeLoop("count") for (int j = 0; j < paletteSize - 1; ++j) {
|
||||
count += used[j];
|
||||
}
|
||||
} while (count >= 256 && --depth);
|
||||
|
||||
MsfCookedFrame ret = { cooked, depth, count, rdepths[depth], gdepths[depth], bdepths[depth] };
|
||||
*frame = ret;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// Frame Compression ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
static inline void msf_put_code(uint8_t * * writeHead, uint32_t * blockBits, int len, uint32_t code) {
|
||||
//insert new code into block buffer
|
||||
int idx = *blockBits / 8;
|
||||
int bit = *blockBits % 8;
|
||||
(*writeHead)[idx + 0] |= code << bit ;
|
||||
(*writeHead)[idx + 1] |= code >> ( 8 - bit);
|
||||
(*writeHead)[idx + 2] |= code >> (16 - bit);
|
||||
*blockBits += len;
|
||||
|
||||
//prep the next block buffer if the current one is full
|
||||
if (*blockBits >= 256 * 8) {
|
||||
*blockBits -= 255 * 8;
|
||||
(*writeHead) += 256;
|
||||
(*writeHead)[2] = (*writeHead)[1];
|
||||
(*writeHead)[1] = (*writeHead)[0];
|
||||
(*writeHead)[0] = 255;
|
||||
memset((*writeHead) + 4, 0, 256);
|
||||
}
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
int16_t * data;
|
||||
int len;
|
||||
int stride;
|
||||
} MsfStridedList;
|
||||
|
||||
static inline void msf_lzw_reset(MsfStridedList * lzw, int tableSize, int stride) { MsfTimeFunc
|
||||
memset(lzw->data, 0xFF, 4096 * stride * sizeof(int16_t));
|
||||
lzw->len = tableSize + 2;
|
||||
lzw->stride = stride;
|
||||
}
|
||||
|
||||
static MsfGifBuffer * msf_compress_frame(void * allocContext, int width, int height, int centiSeconds,
|
||||
MsfCookedFrame frame, MsfGifState * handle, uint8_t * used, int16_t * lzwMem)
|
||||
{ MsfTimeFunc
|
||||
//NOTE: we reserve enough memory for theoretical the worst case upfront because it's a reasonable amount,
|
||||
// and prevents us from ever having to check size or realloc during compression
|
||||
int maxBufSize = offsetof(MsfGifBuffer, data) + 32 + 256 * 3 + width * height * 3 / 2; //headers + color table + data
|
||||
MsfGifBuffer * buffer = (MsfGifBuffer *) MSF_GIF_MALLOC(allocContext, maxBufSize);
|
||||
if (!buffer) { return NULL; }
|
||||
uint8_t * writeHead = buffer->data;
|
||||
MsfStridedList lzw = { lzwMem };
|
||||
|
||||
//allocate tlb
|
||||
int totalBits = frame.rbits + frame.gbits + frame.bbits;
|
||||
int tlbSize = (1 << totalBits) + 1;
|
||||
uint8_t tlb[(1 << 16) + 1]; //only 64k, so stack allocating is fine
|
||||
|
||||
//generate palette
|
||||
typedef struct { uint8_t r, g, b; } Color3;
|
||||
Color3 table[256] = { {0} };
|
||||
int tableIdx = 1; //we start counting at 1 because 0 is the transparent color
|
||||
//transparent is always last in the table
|
||||
tlb[tlbSize-1] = 0;
|
||||
MsfTimeLoop("table") for (int i = 0; i < tlbSize-1; ++i) {
|
||||
if (used[i]) {
|
||||
tlb[i] = tableIdx;
|
||||
int rmask = (1 << frame.rbits) - 1;
|
||||
int gmask = (1 << frame.gbits) - 1;
|
||||
//isolate components
|
||||
int r = i & rmask;
|
||||
int g = i >> frame.rbits & gmask;
|
||||
int b = i >> (frame.rbits + frame.gbits);
|
||||
//shift into highest bits
|
||||
r <<= 8 - frame.rbits;
|
||||
g <<= 8 - frame.gbits;
|
||||
b <<= 8 - frame.bbits;
|
||||
table[tableIdx].r = r | r >> frame.rbits | r >> (frame.rbits * 2) | r >> (frame.rbits * 3);
|
||||
table[tableIdx].g = g | g >> frame.gbits | g >> (frame.gbits * 2) | g >> (frame.gbits * 3);
|
||||
table[tableIdx].b = b | b >> frame.bbits | b >> (frame.bbits * 2) | b >> (frame.bbits * 3);
|
||||
if (msf_gif_bgra_flag) {
|
||||
uint8_t temp = table[tableIdx].r;
|
||||
table[tableIdx].r = table[tableIdx].b;
|
||||
table[tableIdx].b = temp;
|
||||
}
|
||||
++tableIdx;
|
||||
}
|
||||
}
|
||||
int hasTransparentPixels = used[tlbSize-1];
|
||||
|
||||
//SPEC: "Because of some algorithmic constraints however, black & white images which have one color bit
|
||||
// must be indicated as having a code size of 2."
|
||||
int tableBits = msf_imax(2, msf_bit_log(tableIdx - 1));
|
||||
int tableSize = 1 << tableBits;
|
||||
//NOTE: we don't just compare `depth` field here because it will be wrong for the first frame and we will segfault
|
||||
MsfCookedFrame previous = handle->previousFrame;
|
||||
int hasSamePal = frame.rbits == previous.rbits && frame.gbits == previous.gbits && frame.bbits == previous.bbits;
|
||||
int framesCompatible = hasSamePal && !hasTransparentPixels;
|
||||
|
||||
//NOTE: because __attribute__((__packed__)) is annoyingly compiler-specific, we do this unreadable weirdness
|
||||
char headerBytes[19] = "\x21\xF9\x04\x05\0\0\0\0" "\x2C\0\0\0\0\0\0\0\0\x80";
|
||||
//NOTE: we need to check the frame number because if we reach into the buffer prior to the first frame,
|
||||
// we'll just clobber the file header instead, which is a bug
|
||||
if (hasTransparentPixels && handle->framesSubmitted > 0) {
|
||||
handle->listTail->data[3] = 0x09; //set the previous frame's disposal to background, so transparency is possible
|
||||
}
|
||||
memcpy(&headerBytes[4], ¢iSeconds, 2);
|
||||
memcpy(&headerBytes[13], &width, 2);
|
||||
memcpy(&headerBytes[15], &height, 2);
|
||||
headerBytes[17] |= tableBits - 1;
|
||||
memcpy(writeHead, headerBytes, 18);
|
||||
writeHead += 18;
|
||||
|
||||
//local color table
|
||||
memcpy(writeHead, table, tableSize * sizeof(Color3));
|
||||
writeHead += tableSize * sizeof(Color3);
|
||||
*writeHead++ = tableBits;
|
||||
|
||||
//prep block
|
||||
memset(writeHead, 0, 260);
|
||||
writeHead[0] = 255;
|
||||
uint32_t blockBits = 8; //relative to block.head
|
||||
|
||||
//SPEC: "Encoders should output a Clear code as the first code of each image data stream."
|
||||
msf_lzw_reset(&lzw, tableSize, tableIdx);
|
||||
msf_put_code(&writeHead, &blockBits, msf_bit_log(lzw.len - 1), tableSize);
|
||||
|
||||
int lastCode = framesCompatible && frame.pixels[0] == previous.pixels[0]? 0 : tlb[frame.pixels[0]];
|
||||
MsfTimeLoop("compress") for (int i = 1; i < width * height; ++i) {
|
||||
//PERF: branching vs. branchless version of this line is observed to have no discernable impact on speed
|
||||
int color = framesCompatible && frame.pixels[i] == previous.pixels[i]? 0 : tlb[frame.pixels[i]];
|
||||
int code = (&lzw.data[lastCode * lzw.stride])[color];
|
||||
if (code < 0) {
|
||||
//write to code stream
|
||||
int codeBits = msf_bit_log(lzw.len - 1);
|
||||
msf_put_code(&writeHead, &blockBits, codeBits, lastCode);
|
||||
|
||||
if (lzw.len > 4095) {
|
||||
//reset buffer code table
|
||||
msf_put_code(&writeHead, &blockBits, codeBits, tableSize);
|
||||
msf_lzw_reset(&lzw, tableSize, tableIdx);
|
||||
} else {
|
||||
(&lzw.data[lastCode * lzw.stride])[color] = lzw.len;
|
||||
++lzw.len;
|
||||
}
|
||||
|
||||
lastCode = color;
|
||||
} else {
|
||||
lastCode = code;
|
||||
}
|
||||
}
|
||||
|
||||
//write code for leftover index buffer contents, then the end code
|
||||
msf_put_code(&writeHead, &blockBits, msf_imin(12, msf_bit_log(lzw.len - 1)), lastCode);
|
||||
msf_put_code(&writeHead, &blockBits, msf_imin(12, msf_bit_log(lzw.len)), tableSize + 1);
|
||||
|
||||
//flush remaining data
|
||||
if (blockBits > 8) {
|
||||
int bytes = (blockBits + 7) / 8; //round up
|
||||
writeHead[0] = bytes - 1;
|
||||
writeHead += bytes;
|
||||
}
|
||||
*writeHead++ = 0; //terminating block
|
||||
|
||||
//fill in buffer header and shrink buffer to fit data
|
||||
buffer->next = NULL;
|
||||
buffer->size = writeHead - buffer->data;
|
||||
MsfGifBuffer * moved =
|
||||
(MsfGifBuffer *) MSF_GIF_REALLOC(allocContext, buffer, maxBufSize, offsetof(MsfGifBuffer, data) + buffer->size);
|
||||
if (!moved) { MSF_GIF_FREE(allocContext, buffer, maxBufSize); return NULL; }
|
||||
return moved;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// To-memory API ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
static const int lzwAllocSize = 4096 * 256 * sizeof(int16_t);
|
||||
|
||||
//NOTE: by C standard library conventions, freeing NULL should be a no-op,
|
||||
// but just in case the user's custom free doesn't follow that rule, we do null checks on our end as well.
|
||||
static void msf_free_gif_state(MsfGifState * handle) {
|
||||
if (handle->previousFrame.pixels) MSF_GIF_FREE(handle->customAllocatorContext, handle->previousFrame.pixels,
|
||||
handle->width * handle->height * sizeof(uint32_t));
|
||||
if (handle->currentFrame.pixels) MSF_GIF_FREE(handle->customAllocatorContext, handle->currentFrame.pixels,
|
||||
handle->width * handle->height * sizeof(uint32_t));
|
||||
if (handle->lzwMem) MSF_GIF_FREE(handle->customAllocatorContext, handle->lzwMem, lzwAllocSize);
|
||||
for (MsfGifBuffer * node = handle->listHead; node;) {
|
||||
MsfGifBuffer * next = node->next; //NOTE: we have to copy the `next` pointer BEFORE freeing the node holding it
|
||||
MSF_GIF_FREE(handle->customAllocatorContext, node, offsetof(MsfGifBuffer, data) + node->size);
|
||||
node = next;
|
||||
}
|
||||
handle->listHead = NULL; //this implicitly marks the handle as invalid until the next msf_gif_begin() call
|
||||
}
|
||||
|
||||
int msf_gif_begin(MsfGifState * handle, int width, int height) { MsfTimeFunc
|
||||
//NOTE: we cannot stomp the entire struct to zero because we must preserve `customAllocatorContext`.
|
||||
MsfCookedFrame empty = {0}; //god I hate MSVC...
|
||||
handle->previousFrame = empty;
|
||||
handle->currentFrame = empty;
|
||||
handle->width = width;
|
||||
handle->height = height;
|
||||
handle->framesSubmitted = 0;
|
||||
|
||||
//allocate memory for LZW buffer
|
||||
//NOTE: Unfortunately we can't just use stack memory for the LZW table because it's 2MB,
|
||||
// which is more stack space than most operating systems give by default,
|
||||
// and we can't realistically expect users to be willing to override that just to use our library,
|
||||
// so we have to allocate this on the heap.
|
||||
handle->lzwMem = (int16_t *) MSF_GIF_MALLOC(handle->customAllocatorContext, lzwAllocSize);
|
||||
handle->previousFrame.pixels =
|
||||
(uint32_t *) MSF_GIF_MALLOC(handle->customAllocatorContext, handle->width * handle->height * sizeof(uint32_t));
|
||||
handle->currentFrame.pixels =
|
||||
(uint32_t *) MSF_GIF_MALLOC(handle->customAllocatorContext, handle->width * handle->height * sizeof(uint32_t));
|
||||
|
||||
//setup header buffer header (lol)
|
||||
handle->listHead = (MsfGifBuffer *) MSF_GIF_MALLOC(handle->customAllocatorContext, offsetof(MsfGifBuffer, data) + 32);
|
||||
if (!handle->listHead || !handle->lzwMem || !handle->previousFrame.pixels || !handle->currentFrame.pixels) {
|
||||
msf_free_gif_state(handle);
|
||||
return 0;
|
||||
}
|
||||
handle->listTail = handle->listHead;
|
||||
handle->listHead->next = NULL;
|
||||
handle->listHead->size = 32;
|
||||
|
||||
//NOTE: because __attribute__((__packed__)) is annoyingly compiler-specific, we do this unreadable weirdness
|
||||
char headerBytes[33] = "GIF89a\0\0\0\0\x70\0\0" "\x21\xFF\x0BNETSCAPE2.0\x03\x01\0\0\0";
|
||||
memcpy(&headerBytes[6], &width, 2);
|
||||
memcpy(&headerBytes[8], &height, 2);
|
||||
memcpy(handle->listHead->data, headerBytes, 32);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int msf_gif_frame(MsfGifState * handle, uint8_t * pixelData, int centiSecondsPerFame, int maxBitDepth, int pitchInBytes)
|
||||
{ MsfTimeFunc
|
||||
if (!handle->listHead) { return 0; }
|
||||
|
||||
maxBitDepth = msf_imax(1, msf_imin(16, maxBitDepth));
|
||||
if (pitchInBytes == 0) pitchInBytes = handle->width * 4;
|
||||
if (pitchInBytes < 0) pixelData -= pitchInBytes * (handle->height - 1);
|
||||
|
||||
uint8_t used[(1 << 16) + 1]; //only 64k, so stack allocating is fine
|
||||
msf_cook_frame(&handle->currentFrame, pixelData, used, handle->width, handle->height, pitchInBytes,
|
||||
msf_imin(maxBitDepth, handle->previousFrame.depth + 160 / msf_imax(1, handle->previousFrame.count)));
|
||||
|
||||
MsfGifBuffer * buffer = msf_compress_frame(handle->customAllocatorContext, handle->width, handle->height,
|
||||
centiSecondsPerFame, handle->currentFrame, handle, used, handle->lzwMem);
|
||||
if (!buffer) { msf_free_gif_state(handle); return 0; }
|
||||
handle->listTail->next = buffer;
|
||||
handle->listTail = buffer;
|
||||
|
||||
//swap current and previous frames
|
||||
MsfCookedFrame tmp = handle->previousFrame;
|
||||
handle->previousFrame = handle->currentFrame;
|
||||
handle->currentFrame = tmp;
|
||||
|
||||
handle->framesSubmitted += 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
MsfGifResult msf_gif_end(MsfGifState * handle) { MsfTimeFunc
|
||||
if (!handle->listHead) { MsfGifResult empty = {0}; return empty; }
|
||||
|
||||
//first pass: determine total size
|
||||
size_t total = 1; //1 byte for trailing marker
|
||||
for (MsfGifBuffer * node = handle->listHead; node; node = node->next) { total += node->size; }
|
||||
|
||||
//second pass: write data
|
||||
uint8_t * buffer = (uint8_t *) MSF_GIF_MALLOC(handle->customAllocatorContext, total);
|
||||
if (buffer) {
|
||||
uint8_t * writeHead = buffer;
|
||||
for (MsfGifBuffer * node = handle->listHead; node; node = node->next) {
|
||||
memcpy(writeHead, node->data, node->size);
|
||||
writeHead += node->size;
|
||||
}
|
||||
*writeHead++ = 0x3B;
|
||||
}
|
||||
|
||||
//third pass: free buffers
|
||||
msf_free_gif_state(handle);
|
||||
|
||||
MsfGifResult ret = { buffer, total, total, handle->customAllocatorContext };
|
||||
return ret;
|
||||
}
|
||||
|
||||
void msf_gif_free(MsfGifResult result) { MsfTimeFunc
|
||||
if (result.data) { MSF_GIF_FREE(result.contextPointer, result.data, result.allocSize); }
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// To-file API ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
int msf_gif_begin_to_file(MsfGifState * handle, int width, int height, MsfGifFileWriteFunc func, void * filePointer) {
|
||||
handle->fileWriteFunc = func;
|
||||
handle->fileWriteData = filePointer;
|
||||
return msf_gif_begin(handle, width, height);
|
||||
}
|
||||
|
||||
int msf_gif_frame_to_file(MsfGifState * handle, uint8_t * pixelData, int centiSecondsPerFame, int maxBitDepth, int pitchInBytes) {
|
||||
if (!msf_gif_frame(handle, pixelData, centiSecondsPerFame, maxBitDepth, pitchInBytes)) { return 0; }
|
||||
|
||||
//NOTE: this is a somewhat hacky implementation which is not perfectly efficient, but it's good enough for now
|
||||
MsfGifBuffer * head = handle->listHead;
|
||||
if (!handle->fileWriteFunc(head->data, head->size, 1, handle->fileWriteData)) { msf_free_gif_state(handle); return 0; }
|
||||
handle->listHead = head->next;
|
||||
MSF_GIF_FREE(handle->customAllocatorContext, head, offsetof(MsfGifBuffer, data) + head->size);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int msf_gif_end_to_file(MsfGifState * handle) {
|
||||
//NOTE: this is a somewhat hacky implementation which is not perfectly efficient, but it's good enough for now
|
||||
MsfGifResult result = msf_gif_end(handle);
|
||||
int ret = (int) handle->fileWriteFunc(result.data, result.dataSize, 1, handle->fileWriteData);
|
||||
msf_gif_free(result);
|
||||
return ret;
|
||||
}
|
||||
|
||||
#endif //MSF_GIF_ALREADY_IMPLEMENTED_IN_THIS_TRANSLATION_UNIT
|
||||
#endif //MSF_GIF_IMPL
|
||||
|
||||
/*
|
||||
------------------------------------------------------------------------------
|
||||
This software is available under 2 licenses -- choose whichever you prefer.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE A - MIT License
|
||||
Copyright (c) 2021 Miles Fogle
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||
This is free and unencumbered software released into the public domain.
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
software, either in source code form or as a compiled binary, for any purpose,
|
||||
commercial or non-commercial, and by any means.
|
||||
In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
software dedicate any and all copyright interest in the software to the public
|
||||
domain. We make this dedication for the benefit of the public at large and to
|
||||
the detriment of our heirs and successors. We intend this dedication to be an
|
||||
overt act of relinquishment in perpetuity of all present and future rights to
|
||||
this software under copyright law.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
*/
|
||||
3098
source/nanosvg.h
3098
source/nanosvg.h
File diff suppressed because it is too large
Load Diff
1459
source/nanosvgrast.h
1459
source/nanosvgrast.h
File diff suppressed because it is too large
Load Diff
@@ -1,52 +0,0 @@
|
||||
#ifndef QJS_COMMON_H
|
||||
#define QJS_COMMON_H
|
||||
|
||||
#include "cell.h"
|
||||
#include "HandmadeMath.h"
|
||||
#include "render.h"
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
// Forward declarations
|
||||
typedef struct sprite sprite;
|
||||
typedef struct transform transform;
|
||||
|
||||
// Common conversion functions - to JavaScript
|
||||
JSValue vec22js(JSContext *js, HMM_Vec2 v);
|
||||
JSValue vec32js(JSContext *js, HMM_Vec3 v);
|
||||
JSValue vec42js(JSContext *js, HMM_Vec4 v);
|
||||
JSValue rect2js(JSContext *js, rect r);
|
||||
JSValue number2js(JSContext *js, double n);
|
||||
|
||||
// Common conversion functions - from JavaScript
|
||||
HMM_Vec2 js2vec2(JSContext *js, JSValue v);
|
||||
HMM_Vec3 js2vec3(JSContext *js, JSValue v);
|
||||
HMM_Vec4 js2vec4(JSContext *js, JSValue v);
|
||||
rect js2rect(JSContext *js, JSValue v);
|
||||
irect js2irect(JSContext *js, JSValue v);
|
||||
colorf js2color(JSContext *js, JSValue v);
|
||||
double js2number(JSContext *js, JSValue v);
|
||||
sprite *js2sprite(JSContext *js, JSValue v);
|
||||
transform *js2transform(JSContext *js, JSValue v);
|
||||
|
||||
// SDL type conversion functions
|
||||
SDL_Window *js2SDL_Window(JSContext *js, JSValue v);
|
||||
SDL_Renderer *js2SDL_Renderer(JSContext *js, JSValue v);
|
||||
SDL_Texture *js2SDL_Texture(JSContext *js, JSValue v);
|
||||
SDL_ScaleMode js2SDL_ScaleMode(JSContext *js, JSValue v);
|
||||
|
||||
JSValue SDL_Window2js(JSContext *js, SDL_Window *w);
|
||||
JSValue SDL_Renderer2js(JSContext *js, SDL_Renderer *r);
|
||||
JSValue SDL_Texture2js(JSContext *js, SDL_Texture *t);
|
||||
|
||||
// GPU buffer functions
|
||||
JSValue make_gpu_buffer(JSContext *js, void *data, size_t size, int type, int elements, int copy, int index);
|
||||
void *get_gpu_buffer(JSContext *js, JSValue argv, size_t *stride, size_t *size);
|
||||
JSValue make_quad_indices_buffer(JSContext *js, int quads);
|
||||
|
||||
// Matrix conversion
|
||||
HMM_Mat3 transform2mat3(transform *t);
|
||||
|
||||
// Utility functions
|
||||
double js_getnum_str(JSContext *js, JSValue v, const char *str);
|
||||
|
||||
#endif /* QJS_COMMON_H */
|
||||
@@ -1,132 +0,0 @@
|
||||
#include "cell.h"
|
||||
#define DMON_IMPL
|
||||
#include "dmon.h"
|
||||
|
||||
// Define the file event structure and completion queue
|
||||
typedef struct {
|
||||
dmon_action action;
|
||||
char rootdir[256];
|
||||
char filepath[256];
|
||||
char oldfilepath[256];
|
||||
} FileEvent;
|
||||
|
||||
typedef struct EventNode {
|
||||
FileEvent event;
|
||||
struct EventNode *next;
|
||||
} EventNode;
|
||||
|
||||
typedef struct {
|
||||
EventNode *head;
|
||||
EventNode *tail;
|
||||
} CompletionQueue;
|
||||
|
||||
CompletionQueue completionQueue = { NULL, NULL };
|
||||
|
||||
// Helper functions for the completion queue
|
||||
void enqueue_event(FileEvent event) {
|
||||
EventNode *node = malloc(sizeof(EventNode));
|
||||
node->event = event;
|
||||
node->next = NULL;
|
||||
|
||||
if (completionQueue.tail) {
|
||||
completionQueue.tail->next = node;
|
||||
} else {
|
||||
completionQueue.head = node;
|
||||
}
|
||||
completionQueue.tail = node;
|
||||
}
|
||||
|
||||
int dequeue_event(FileEvent *event) {
|
||||
if (!completionQueue.head) {
|
||||
return 0; // No event
|
||||
}
|
||||
EventNode *node = completionQueue.head;
|
||||
*event = node->event;
|
||||
completionQueue.head = node->next;
|
||||
if (!completionQueue.head) {
|
||||
completionQueue.tail = NULL;
|
||||
}
|
||||
free(node);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void watch_cb(dmon_watch_id id, dmon_action action, const char *rootdir, const char *filepath, const char *oldfilepath, void *user)
|
||||
{
|
||||
FileEvent event;
|
||||
event.action = action;
|
||||
strncpy(event.rootdir, rootdir, sizeof(event.rootdir) - 1);
|
||||
strncpy(event.filepath, filepath, sizeof(event.filepath) - 1);
|
||||
if (oldfilepath) {
|
||||
strncpy(event.oldfilepath, oldfilepath, sizeof(event.oldfilepath) - 1);
|
||||
} else {
|
||||
event.oldfilepath[0] = '\0';
|
||||
}
|
||||
enqueue_event(event); // Add event to completion queue
|
||||
}
|
||||
|
||||
static dmon_watch_id watched = {0};
|
||||
|
||||
JSValue js_dmon_watch(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
if (watched.id)
|
||||
return JS_ThrowReferenceError(js, "Already watching a directory.");
|
||||
|
||||
watched = dmon_watch(".", watch_cb, DMON_WATCHFLAGS_RECURSIVE, NULL);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_dmon_unwatch(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
if (!watched.id)
|
||||
return JS_ThrowReferenceError(js, "Not watching a directory.");
|
||||
|
||||
dmon_unwatch(watched);
|
||||
watched.id = 0;
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_dmon_poll(JSContext *js, JSValueConst this_val, int argc, JSValueConst *argv) {
|
||||
FileEvent event;
|
||||
while (dequeue_event(&event)) {
|
||||
if (!JS_IsFunction(js, argv[0])) continue;
|
||||
JSValue jsevent = JS_NewObject(js);
|
||||
JSValue action;
|
||||
switch(event.action) {
|
||||
case DMON_ACTION_CREATE:
|
||||
action = JS_NewAtomString(js, "create");
|
||||
break;
|
||||
case DMON_ACTION_DELETE:
|
||||
action = JS_NewAtomString(js, "delete");
|
||||
break;
|
||||
case DMON_ACTION_MODIFY:
|
||||
action = JS_NewAtomString(js, "modify");
|
||||
break;
|
||||
case DMON_ACTION_MOVE:
|
||||
action = JS_NewAtomString(js, "move");
|
||||
break;
|
||||
}
|
||||
JS_SetPropertyStr(js, jsevent, "action", action);
|
||||
JS_SetPropertyStr(js, jsevent, "root", JS_NewString(js, event.rootdir));
|
||||
JS_SetPropertyStr(js, jsevent, "file", JS_NewString(js, event.filepath));
|
||||
JS_SetPropertyStr(js, jsevent, "old", JS_NewString(js, event.oldfilepath));
|
||||
JS_Call(js, argv[0], JS_NULL, 1, &jsevent);
|
||||
JS_FreeValue(js, jsevent);
|
||||
}
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static const JSCFunctionListEntry js_dmon_funcs[] = {
|
||||
JS_CFUNC_DEF("watch", 0, js_dmon_watch),
|
||||
JS_CFUNC_DEF("unwatch", 0, js_dmon_unwatch),
|
||||
JS_CFUNC_DEF("poll", 1, js_dmon_poll)
|
||||
};
|
||||
|
||||
JSValue js_dmon_use(JSContext *js)
|
||||
{
|
||||
JSValue export = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, export, js_dmon_funcs, sizeof(js_dmon_funcs)/sizeof(JSCFunctionListEntry));
|
||||
|
||||
dmon_init();
|
||||
|
||||
return export;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
#include "cell.h"
|
||||
#define PAR_EASYCURL_IMPLEMENTATION
|
||||
#include "thirdparty/par/par_easycurl.h"
|
||||
#include "par_easycurl.h"
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
1073
source/qjs_imgui.cpp
1073
source/qjs_imgui.cpp
File diff suppressed because it is too large
Load Diff
@@ -1,17 +0,0 @@
|
||||
#ifndef QJS_IMGUI_H
|
||||
#define QJS_IMGUI_H
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Function to process SDL events for ImGui
|
||||
void gui_input(SDL_Event *e);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // QJS_IMGUI_H
|
||||
@@ -1,232 +0,0 @@
|
||||
#include "quickjs.h"
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
|
||||
#define LAY_FLOAT 1
|
||||
#define LAY_IMPLEMENTATION
|
||||
#include "layout.h"
|
||||
|
||||
static JSClassID js_layout_class_id;
|
||||
|
||||
#define GETLAY \
|
||||
lay_context *lay = JS_GetOpaque2(js, self, js_layout_class_id); \
|
||||
if (!lay) return JS_EXCEPTION;
|
||||
|
||||
#define GETITEM(VAR, ARG) \
|
||||
lay_id VAR; \
|
||||
if (JS_ToUint32(js, &VAR, ARG)) return JS_EXCEPTION; \
|
||||
|
||||
static JSValue js_layout_context_new(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
lay_context *lay = js_malloc(js, sizeof(*lay));
|
||||
lay_init_context(lay);
|
||||
JSValue obj = JS_NewObjectClass(js, js_layout_class_id);
|
||||
JS_SetOpaque(obj, lay);
|
||||
return obj;
|
||||
}
|
||||
|
||||
static JSValue js_layout_item(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
GETLAY
|
||||
lay_id item_id = lay_item(lay);
|
||||
return JS_NewUint32(js,item_id);
|
||||
}
|
||||
|
||||
static JSValue js_layout_set_size(JSContext *js, JSValueConst self, int argc, JSValueConst *argv)
|
||||
{
|
||||
if (argc < 2) return JS_EXCEPTION;
|
||||
|
||||
GETLAY
|
||||
GETITEM(id, argv[0])
|
||||
double width = 0, height = 0;
|
||||
|
||||
// Check if it's an array (for backwards compatibility)
|
||||
if (JS_IsArray(js, argv[1])) {
|
||||
JSValue width_val = JS_GetPropertyUint32(js, argv[1], 0);
|
||||
JSValue height_val = JS_GetPropertyUint32(js, argv[1], 1);
|
||||
JS_ToFloat64(js, &width, width_val);
|
||||
JS_ToFloat64(js, &height, height_val);
|
||||
JS_FreeValue(js, width_val);
|
||||
JS_FreeValue(js, height_val);
|
||||
} else {
|
||||
// Handle object with x,y or width,height properties
|
||||
JSValue width_val = JS_GetPropertyStr(js, argv[1], "width");
|
||||
if (JS_IsNull(width_val)) {
|
||||
width_val = JS_GetPropertyStr(js, argv[1], "x");
|
||||
}
|
||||
JSValue height_val = JS_GetPropertyStr(js, argv[1], "height");
|
||||
if (JS_IsNull(height_val)) {
|
||||
height_val = JS_GetPropertyStr(js, argv[1], "y");
|
||||
}
|
||||
JS_ToFloat64(js, &width, width_val);
|
||||
JS_ToFloat64(js, &height, height_val);
|
||||
JS_FreeValue(js, width_val);
|
||||
JS_FreeValue(js, height_val);
|
||||
}
|
||||
|
||||
if (isnan(width)) width = 0;
|
||||
if (isnan(height)) height = 0;
|
||||
lay_set_size_xy(lay, id, width, height);
|
||||
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_layout_set_behave(JSContext *js, JSValueConst self, int argc, JSValueConst *argv)
|
||||
{
|
||||
GETLAY
|
||||
GETITEM(id, argv[0])
|
||||
uint32_t behave_flags;
|
||||
JS_ToUint32(js, &behave_flags, argv[1]);
|
||||
lay_set_behave(lay, id, behave_flags);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_layout_set_contain(JSContext *js, JSValueConst self, int argc, JSValueConst *argv)
|
||||
{
|
||||
GETLAY
|
||||
GETITEM(id, argv[0])
|
||||
uint32_t contain_flags;
|
||||
JS_ToUint32(js, &contain_flags, argv[1]);
|
||||
lay_set_contain(lay, id, contain_flags);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
#define PULLMARGIN(DIR,MARGIN) \
|
||||
JSValue js_##DIR = JS_GetPropertyStr(js, argv[1], #DIR); \
|
||||
if (!JS_IsNull(js_##DIR)) { \
|
||||
JS_ToFloat64(js, &margins[MARGIN], js_##DIR); \
|
||||
if (isnan(margins[MARGIN])) margins[MARGIN] = 0; \
|
||||
JS_FreeValue(js, js_##DIR); \
|
||||
}\
|
||||
|
||||
static JSValue js_layout_set_margins(JSContext *js, JSValueConst self, int argc, JSValueConst *argv)
|
||||
{
|
||||
GETLAY
|
||||
GETITEM(id, argv[0])
|
||||
double margins[4] = {0};
|
||||
PULLMARGIN(l,0)
|
||||
PULLMARGIN(r,2)
|
||||
PULLMARGIN(t,1)
|
||||
PULLMARGIN(b,3)
|
||||
lay_set_margins_ltrb(lay, id, margins[0], margins[1], margins[2], margins[3]);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_layout_insert(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
GETLAY
|
||||
GETITEM(parent, argv[0])
|
||||
GETITEM(child, argv[1])
|
||||
lay_insert(lay, parent, child);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_layout_append(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
GETLAY
|
||||
GETITEM(earlier, argv[0])
|
||||
GETITEM(later, argv[1])
|
||||
lay_append(lay, earlier, later);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_layout_push(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
GETLAY
|
||||
GETITEM(parent, argv[0])
|
||||
GETITEM(child, argv[1])
|
||||
lay_push(lay, parent, child);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_layout_run(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
GETLAY
|
||||
lay_run_context(lay);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_layout_get_rect(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
GETLAY
|
||||
GETITEM(id, argv[0])
|
||||
lay_vec4 rect = lay_get_rect(lay, id);
|
||||
JSValue ret = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, ret, "x", JS_NewFloat64(js, rect[0]));
|
||||
JS_SetPropertyStr(js, ret, "y", JS_NewFloat64(js, rect[1]));
|
||||
JS_SetPropertyStr(js, ret, "width", JS_NewFloat64(js, rect[2]));
|
||||
JS_SetPropertyStr(js, ret, "height", JS_NewFloat64(js, rect[3]));
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
static JSValue js_layout_reset(JSContext *js, JSValueConst self, int argc, JSValueConst *argv) {
|
||||
GETLAY
|
||||
lay_reset_context(lay);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static void js_layout_finalizer(JSRuntime *rt, JSValue val) {
|
||||
lay_context *ctx = JS_GetOpaque(val, js_layout_class_id);
|
||||
lay_destroy_context(ctx);
|
||||
js_free_rt(rt, ctx);
|
||||
}
|
||||
|
||||
static JSClassDef js_layout_class = {
|
||||
"layout_context",
|
||||
.finalizer = js_layout_finalizer,
|
||||
};
|
||||
|
||||
static const JSCFunctionListEntry js_layout_proto_funcs[] = {
|
||||
JS_CFUNC_DEF("item", 1, js_layout_item),
|
||||
JS_CFUNC_DEF("insert", 2, js_layout_insert),
|
||||
JS_CFUNC_DEF("append", 2, js_layout_append),
|
||||
JS_CFUNC_DEF("push", 2, js_layout_push),
|
||||
JS_CFUNC_DEF("run", 0, js_layout_run),
|
||||
JS_CFUNC_DEF("get_rect", 1, js_layout_get_rect),
|
||||
JS_CFUNC_DEF("reset", 0, js_layout_reset),
|
||||
JS_CFUNC_DEF("set_margins", 2, js_layout_set_margins),
|
||||
JS_CFUNC_DEF("set_size", 2, js_layout_set_size),
|
||||
JS_CFUNC_DEF("set_contain", 2, js_layout_set_contain),
|
||||
JS_CFUNC_DEF("set_behave", 2, js_layout_set_behave),
|
||||
};
|
||||
|
||||
static const JSCFunctionListEntry js_layout_funcs[] = {
|
||||
JS_CFUNC_DEF("make_context", 0, js_layout_context_new)
|
||||
};
|
||||
|
||||
JSValue js_layout_use(JSContext *js)
|
||||
{
|
||||
JS_NewClassID(&js_layout_class_id);
|
||||
JS_NewClass(JS_GetRuntime(js), js_layout_class_id, &js_layout_class);
|
||||
|
||||
JSValue proto = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, proto, js_layout_proto_funcs, sizeof(js_layout_proto_funcs) / sizeof(JSCFunctionListEntry));
|
||||
JS_SetClassProto(js, js_layout_class_id, proto);
|
||||
|
||||
JSValue contain = JS_NewObject(js);
|
||||
JSValue behave = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, contain, "row", JS_NewUint32(js, LAY_ROW));
|
||||
JS_SetPropertyStr(js, contain, "column", JS_NewUint32(js, LAY_COLUMN));
|
||||
JS_SetPropertyStr(js, contain, "layout", JS_NewUint32(js, LAY_LAYOUT));
|
||||
JS_SetPropertyStr(js, contain, "flex", JS_NewUint32(js, LAY_FLEX));
|
||||
JS_SetPropertyStr(js, contain, "wrap", JS_NewUint32(js, LAY_WRAP));
|
||||
JS_SetPropertyStr(js, contain, "nowrap", JS_NewUint32(js, LAY_NOWRAP));
|
||||
|
||||
JS_SetPropertyStr(js, contain, "start", JS_NewUint32(js, LAY_START));
|
||||
JS_SetPropertyStr(js, contain, "middle", JS_NewUint32(js, LAY_MIDDLE));
|
||||
JS_SetPropertyStr(js, contain, "end", JS_NewUint32(js, LAY_END));
|
||||
JS_SetPropertyStr(js, contain, "justify", JS_NewUint32(js, LAY_JUSTIFY));
|
||||
|
||||
JS_SetPropertyStr(js, behave, "left", JS_NewUint32(js, LAY_LEFT));
|
||||
JS_SetPropertyStr(js, behave, "top", JS_NewUint32(js, LAY_TOP));
|
||||
JS_SetPropertyStr(js, behave, "right", JS_NewUint32(js, LAY_RIGHT));
|
||||
JS_SetPropertyStr(js, behave, "bottom", JS_NewUint32(js, LAY_BOTTOM));
|
||||
JS_SetPropertyStr(js, behave, "hfill", JS_NewUint32(js, LAY_HFILL));
|
||||
JS_SetPropertyStr(js, behave, "vfill", JS_NewUint32(js, LAY_VFILL));
|
||||
JS_SetPropertyStr(js, behave, "hcenter", JS_NewUint32(js, LAY_HCENTER));
|
||||
JS_SetPropertyStr(js, behave, "vcenter", JS_NewUint32(js, LAY_VCENTER));
|
||||
JS_SetPropertyStr(js, behave, "center", JS_NewUint32(js, LAY_CENTER));
|
||||
JS_SetPropertyStr(js, behave, "fill", JS_NewUint32(js, LAY_FILL));
|
||||
JS_SetPropertyStr(js, behave, "break", JS_NewUint32(js, LAY_BREAK));
|
||||
|
||||
JSValue export = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, export, js_layout_funcs, sizeof(js_layout_funcs)/sizeof(JSCFunctionListEntry));
|
||||
JS_SetPropertyStr(js, export, "behave", behave);
|
||||
JS_SetPropertyStr(js, export, "contain", contain);
|
||||
|
||||
return export;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
#include "cell.h"
|
||||
#include "jsffi.h"
|
||||
#include "qjs_common.h"
|
||||
#include "qjs_wota.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
@@ -1,503 +0,0 @@
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <math.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include "HandmadeMath.h"
|
||||
|
||||
QJSCLASS(SDL_Renderer,)
|
||||
|
||||
rect transform_rect(rect in, HMM_Mat3 *t)
|
||||
{
|
||||
HMM_Vec3 bottom_left = (HMM_Vec3){in.x,in.y,1.0};
|
||||
HMM_Vec3 transformed_bl = HMM_MulM3V3(*t, bottom_left);
|
||||
in.x = transformed_bl.x;
|
||||
in.y = transformed_bl.y;
|
||||
in.y = in.y - in.h; // should be done for any platform that draws rectangles from top left
|
||||
return in;
|
||||
}
|
||||
|
||||
HMM_Vec2 transform_point(SDL_Renderer *ren, HMM_Vec2 in, HMM_Mat3 *t)
|
||||
{
|
||||
rect logical;
|
||||
SDL_GetRenderLogicalPresentationRect(ren, &logical);
|
||||
in.y *= -1;
|
||||
in.y += logical.h;
|
||||
in.x -= t->Columns[2].x;
|
||||
in.y -= t->Columns[2].y;
|
||||
return in;
|
||||
}
|
||||
|
||||
JSC_CCALL(SDL_Renderer_clear,
|
||||
SDL_Renderer *renderer = js2SDL_Renderer(js,self);
|
||||
SDL_RenderClear(renderer);
|
||||
)
|
||||
|
||||
JSC_CCALL(SDL_Renderer_present,
|
||||
SDL_Renderer *ren = js2SDL_Renderer(js,self);
|
||||
SDL_RenderPresent(ren);
|
||||
)
|
||||
|
||||
JSC_CCALL(SDL_Renderer_draw_color,
|
||||
SDL_Renderer *renderer = js2SDL_Renderer(js,self);
|
||||
colorf color = js2color(js,argv[0]);
|
||||
SDL_SetRenderDrawColorFloat(renderer, color.r,color.g,color.b,color.a);
|
||||
)
|
||||
|
||||
JSC_CCALL(SDL_Renderer_rect,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (!JS_IsNull(argv[1])) {
|
||||
colorf color = js2color(js,argv[1]);
|
||||
SDL_SetRenderDrawColorFloat(r, color.r, color.g, color.b, color.a);
|
||||
}
|
||||
|
||||
if (JS_IsArray(js,argv[0])) {
|
||||
int len = JS_ArrayLength(js,argv[0]);
|
||||
rect rects[len];
|
||||
for (int i = 0; i < len; i++) {
|
||||
JSValue val = JS_GetPropertyUint32(js,argv[0],i);
|
||||
rects[i] = transform_rect(js2rect(js,val), &cam_mat);
|
||||
JS_FreeValue(js,val);
|
||||
}
|
||||
SDL_RenderRects(r,rects,len);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
rect rect = js2rect(js,argv[0]);
|
||||
|
||||
rect = transform_rect(rect, &cam_mat);
|
||||
|
||||
SDL_RenderRect(r, &rect);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_load_texture,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
SDL_Surface *surf = js2SDL_Surface(js,argv[0]);
|
||||
if (!surf) return JS_ThrowReferenceError(js, "Surface was not a surface.");
|
||||
SDL_Texture *tex = SDL_CreateTextureFromSurface(r,surf);
|
||||
if (!tex) return JS_ThrowReferenceError(js, "Could not create texture from surface: %s", SDL_GetError());
|
||||
ret = SDL_Texture2js(js,tex);
|
||||
JS_SetPropertyStr(js,ret,"width", number2js(js,tex->w));
|
||||
JS_SetPropertyStr(js,ret,"height", number2js(js,tex->h));
|
||||
)
|
||||
|
||||
JSC_CCALL(SDL_Renderer_fillrect,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (!JS_IsNull(argv[1])) {
|
||||
colorf color = js2color(js,argv[1]);
|
||||
SDL_SetRenderDrawColorFloat(r, color.r, color.g, color.b, color.a);
|
||||
}
|
||||
|
||||
if (JS_IsArray(js,argv[0])) {
|
||||
int len = JS_ArrayLength(js,argv[0]);
|
||||
rect rects[len];
|
||||
for (int i = 0; i < len; i++) {
|
||||
JSValue val = JS_GetPropertyUint32(js,argv[0],i);
|
||||
rects[i] = js2rect(js,val);
|
||||
JS_FreeValue(js,val);
|
||||
}
|
||||
if (!SDL_RenderFillRects(r,rects,len))
|
||||
return JS_ThrowReferenceError(js, "Could not render rectangle: %s", SDL_GetError());
|
||||
}
|
||||
rect rect = transform_rect(js2rect(js,argv[0]),&cam_mat);
|
||||
|
||||
if (!SDL_RenderFillRect(r, &rect))
|
||||
return JS_ThrowReferenceError(js, "Could not render rectangle: %s", SDL_GetError());
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_texture,
|
||||
SDL_Renderer *renderer = js2SDL_Renderer(js,self);
|
||||
SDL_Texture *tex = js2SDL_Texture(js,argv[0]);
|
||||
rect dst = transform_rect(js2rect(js,argv[1]), &cam_mat);
|
||||
|
||||
if (!JS_IsNull(argv[3])) {
|
||||
colorf color = js2color(js,argv[3]);
|
||||
SDL_SetTextureColorModFloat(tex, color.r, color.g, color.b);
|
||||
SDL_SetTextureAlphaModFloat(tex,color.a);
|
||||
}
|
||||
if (JS_IsNull(argv[2]))
|
||||
SDL_RenderTexture(renderer,tex,NULL,&dst);
|
||||
else {
|
||||
|
||||
rect src = js2rect(js,argv[2]);
|
||||
|
||||
SDL_RenderTextureRotated(renderer, tex, &src, &dst, 0, NULL, SDL_FLIP_NONE);
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_tile,
|
||||
SDL_Renderer *renderer = js2SDL_Renderer(js,self);
|
||||
if (!renderer) return JS_ThrowTypeError(js,"self was not a renderer");
|
||||
SDL_Texture *tex = js2SDL_Texture(js,argv[0]);
|
||||
if (!tex) return JS_ThrowTypeError(js,"first argument was not a texture");
|
||||
rect dst = js2rect(js,argv[1]);
|
||||
if (!dst.w) dst.w = tex->w;
|
||||
if (!dst.h) dst.h = tex->h;
|
||||
float scale = js2number(js,argv[3]);
|
||||
if (!scale) scale = 1;
|
||||
if (JS_IsNull(argv[2]))
|
||||
SDL_RenderTextureTiled(renderer,tex,NULL,scale, &dst);
|
||||
else {
|
||||
rect src = js2rect(js,argv[2]);
|
||||
SDL_RenderTextureTiled(renderer,tex,&src,scale, &dst);
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_slice9,
|
||||
SDL_Renderer *renderer = js2SDL_Renderer(js,self);
|
||||
SDL_Texture *tex = js2SDL_Texture(js,argv[0]);
|
||||
lrtb bounds = js2lrtb(js,argv[2]);
|
||||
rect src, dst;
|
||||
src = transform_rect(js2rect(js,argv[3]),&cam_mat);
|
||||
dst = transform_rect(js2rect(js,argv[1]), &cam_mat);
|
||||
|
||||
SDL_RenderTexture9Grid(renderer, tex,
|
||||
JS_IsNull(argv[3]) ? NULL : &src,
|
||||
bounds.l, bounds.r, bounds.t, bounds.b, 0.0,
|
||||
JS_IsNull(argv[1]) ? NULL : &dst);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_get_image,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
SDL_Surface *surf = NULL;
|
||||
if (!JS_IsNull(argv[0])) {
|
||||
rect rect = js2rect(js,argv[0]);
|
||||
surf = SDL_RenderReadPixels(r,&rect);
|
||||
} else
|
||||
surf = SDL_RenderReadPixels(r,NULL);
|
||||
if (!surf) return JS_ThrowReferenceError(js, "could not make surface from renderer");
|
||||
return SDL_Surface2js(js,surf);
|
||||
)
|
||||
|
||||
JSC_SCALL(renderer_fasttext,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (!JS_IsNull(argv[2])) {
|
||||
colorf color = js2color(js,argv[2]);
|
||||
SDL_SetRenderDrawColorFloat(r, color.r, color.g, color.b, color.a);
|
||||
}
|
||||
HMM_Vec2 pos = js2vec2(js,argv[1]);
|
||||
pos.y += 8;
|
||||
HMM_Vec2 tpos = HMM_MulM3V3(cam_mat, (HMM_Vec3){pos.x,pos.y,1}).xy;
|
||||
SDL_RenderDebugText(r, tpos.x, tpos.y, str);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_line,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (!JS_IsNull(argv[1])) {
|
||||
colorf color = js2color(js,argv[1]);
|
||||
SDL_SetRenderDrawColorFloat(r, color.r, color.g, color.b, color.a);
|
||||
}
|
||||
|
||||
if (JS_IsArray(js,argv[0])) {
|
||||
int len = JS_ArrayLength(js,argv[0]);
|
||||
HMM_Vec2 points[len];
|
||||
assert(sizeof(HMM_Vec2) == sizeof(SDL_FPoint));
|
||||
for (int i = 0; i < len; i++) {
|
||||
JSValue val = JS_GetPropertyUint32(js,argv[0],i);
|
||||
points[i] = js2vec2(js,val);
|
||||
JS_FreeValue(js,val);
|
||||
}
|
||||
SDL_RenderLines(r,points,len);
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_point,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (!JS_IsNull(argv[1])) {
|
||||
colorf color = js2color(js,argv[1]);
|
||||
SDL_SetRenderDrawColorFloat(r, color.r, color.g, color.b, color.a);
|
||||
}
|
||||
|
||||
if (JS_IsArray(js,argv[0])) {
|
||||
int len = JS_ArrayLength(js,argv[0]);
|
||||
HMM_Vec2 points[len];
|
||||
assert(sizeof(HMM_Vec2) ==sizeof(SDL_FPoint));
|
||||
for (int i = 0; i < len; i++) {
|
||||
JSValue val = JS_GetPropertyUint32(js,argv[0],i);
|
||||
points[i] = js2vec2(js,val);
|
||||
JS_FreeValue(js,val);
|
||||
}
|
||||
SDL_RenderPoints(r, points, len);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
HMM_Vec2 point = transform_point(r, js2vec2(js,argv[0]), &cam_mat);
|
||||
SDL_RenderPoint(r,point.x,point.y);
|
||||
)
|
||||
|
||||
// Function to translate a list of 2D points
|
||||
void Translate2DPoints(HMM_Vec2 *points, int count, HMM_Vec3 position, HMM_Quat rotation, HMM_Vec3 scale) {
|
||||
// Precompute the 2D rotation matrix from the quaternion
|
||||
float xx = rotation.x * rotation.x;
|
||||
float yy = rotation.y * rotation.y;
|
||||
float zz = rotation.z * rotation.z;
|
||||
float xy = rotation.x * rotation.y;
|
||||
float zw = rotation.z * rotation.w;
|
||||
|
||||
// Extract 2D affine rotation and scaling
|
||||
float m00 = (1.0f - 2.0f * (yy + zz)) * scale.x; // Row 1, Column 1
|
||||
float m01 = (2.0f * (xy + zw)) * scale.y; // Row 1, Column 2
|
||||
float m10 = (2.0f * (xy - zw)) * scale.x; // Row 2, Column 1
|
||||
float m11 = (1.0f - 2.0f * (xx + zz)) * scale.y; // Row 2, Column 2
|
||||
|
||||
// Translation components (ignore the z position)
|
||||
float tx = position.x;
|
||||
float ty = position.y;
|
||||
|
||||
// Transform each point
|
||||
for (int i = 0; i < count; ++i) {
|
||||
HMM_Vec2 p = points[i];
|
||||
points[i].x = m00 * p.x + m01 * p.y + tx;
|
||||
points[i].y = m10 * p.x + m11 * p.y + ty;
|
||||
}
|
||||
}
|
||||
|
||||
// Should take a single struct with pos, color, uv, and indices arrays
|
||||
JSC_CCALL(renderer_geometry,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
JSValue pos = JS_GetPropertyStr(js,argv[1], "pos");
|
||||
JSValue color = JS_GetPropertyStr(js,argv[1], "color");
|
||||
JSValue uv = JS_GetPropertyStr(js,argv[1], "uv");
|
||||
JSValue indices = JS_GetPropertyStr(js,argv[1], "indices");
|
||||
int vertices = js_getnum_str(js, argv[1], "vertices");
|
||||
int count = js_getnum_str(js, argv[1], "count");
|
||||
|
||||
size_t pos_stride, indices_stride, uv_stride, color_stride;
|
||||
void *posdata = get_gpu_buffer(js,pos, &pos_stride, NULL);
|
||||
void *idxdata = get_gpu_buffer(js,indices, &indices_stride, NULL);
|
||||
void *uvdata = get_gpu_buffer(js,uv, &uv_stride, NULL);
|
||||
void *colordata = get_gpu_buffer(js,color,&color_stride, NULL);
|
||||
|
||||
SDL_Texture *tex = js2SDL_Texture(js,argv[0]);
|
||||
|
||||
HMM_Vec2 *trans_pos = malloc(vertices*sizeof(HMM_Vec2));
|
||||
memcpy(trans_pos,posdata, sizeof(HMM_Vec2)*vertices);
|
||||
|
||||
for (int i = 0; i < vertices; i++)
|
||||
trans_pos[i] = HMM_MulM3V3(cam_mat, (HMM_Vec3){trans_pos[i].x, trans_pos[i].y, 1}).xy;
|
||||
|
||||
if (!SDL_RenderGeometryRaw(r, tex, trans_pos, pos_stride,colordata,color_stride,uvdata, uv_stride, vertices, idxdata, count, indices_stride))
|
||||
ret = JS_ThrowReferenceError(js, "Error rendering geometry: %s",SDL_GetError());
|
||||
|
||||
free(trans_pos);
|
||||
|
||||
JS_FreeValue(js,pos);
|
||||
JS_FreeValue(js,color);
|
||||
JS_FreeValue(js,uv);
|
||||
JS_FreeValue(js,indices);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_logical_size,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
HMM_Vec2 v = js2vec2(js,argv[0]);
|
||||
SDL_SetRenderLogicalPresentation(r,v.x,v.y,SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_viewport,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (JS_IsNull(argv[0]))
|
||||
SDL_SetRenderViewport(r,NULL);
|
||||
else {
|
||||
rect view = js2rect(js,argv[0]);
|
||||
SDL_SetRenderViewport(r,&view);
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_get_viewport,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
SDL_Rect vp;
|
||||
SDL_GetRenderViewport(r, &vp);
|
||||
rect re;
|
||||
re.x = vp.x;
|
||||
re.y = vp.y;
|
||||
re.h = vp.h;
|
||||
re.w = vp.w;
|
||||
return rect2js(js,re);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_clip,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (JS_IsNull(argv[0]))
|
||||
SDL_SetRenderClipRect(r,NULL);
|
||||
else {
|
||||
rect view = js2rect(js,argv[0]);
|
||||
SDL_SetRenderClipRect(r,&view);
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_scale,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
HMM_Vec2 v = js2vec2(js,argv[0]);
|
||||
SDL_SetRenderScale(r, v.x, v.y);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_vsync,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
SDL_SetRenderVSync(r,js2number(js,argv[0]));
|
||||
)
|
||||
|
||||
// This returns the coordinates inside the
|
||||
JSC_CCALL(renderer_coords,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
HMM_Vec2 pos, coord;
|
||||
pos = js2vec2(js,argv[0]);
|
||||
SDL_RenderCoordinatesFromWindow(r,pos.x,pos.y, &coord.x, &coord.y);
|
||||
return vec22js(js,coord);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_camera,
|
||||
int centered = JS_ToBool(js,argv[1]);
|
||||
SDL_Renderer *ren = js2SDL_Renderer(js,self);
|
||||
SDL_Rect vp;
|
||||
SDL_GetRenderViewport(ren, &vp);
|
||||
HMM_Mat3 proj;
|
||||
proj.Columns[0] = (HMM_Vec3){1,0,0};
|
||||
proj.Columns[1] = (HMM_Vec3){0,-1,0};
|
||||
if (centered)
|
||||
proj.Columns[2] = (HMM_Vec3){vp.w/2.0,vp.h/2.0,1};
|
||||
else
|
||||
proj.Columns[2] = (HMM_Vec3){0,vp.h,1};
|
||||
|
||||
transform *tra = js2transform(js,argv[0]);
|
||||
HMM_Mat3 view;
|
||||
view.Columns[0] = (HMM_Vec3){1,0,0};
|
||||
view.Columns[1] = (HMM_Vec3){0,1,0};
|
||||
view.Columns[2] = (HMM_Vec3){-tra->pos.x, -tra->pos.y,1};
|
||||
cam_mat = HMM_MulM3(proj,view);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_screen2world,
|
||||
HMM_Mat3 inv = HMM_InvGeneralM3(cam_mat);
|
||||
HMM_Vec3 pos = js2vec3(js,argv[0]);
|
||||
return vec22js(js, HMM_MulM3V3(inv, pos).xy);
|
||||
)
|
||||
|
||||
JSC_CCALL(renderer_target,
|
||||
SDL_Renderer *r = js2SDL_Renderer(js,self);
|
||||
if (JS_IsNull(argv[0]))
|
||||
SDL_SetRenderTarget(r, NULL);
|
||||
else {
|
||||
SDL_Texture *tex = js2SDL_Texture(js,argv[0]);
|
||||
SDL_SetRenderTarget(r,tex);
|
||||
}
|
||||
)
|
||||
|
||||
// Given an array of sprites, make the necessary geometry
|
||||
// A sprite is expected to have:
|
||||
// transform: a transform encoding position and rotation. its scale is in pixels - so a scale of 1 means the image will draw only on a single pixel.
|
||||
// image: a standard prosperon image of a surface, rect, and texture
|
||||
// color: the color this sprite should be hued by
|
||||
JSC_CCALL(renderer_make_sprite_mesh,
|
||||
JSValue sprites = argv[0];
|
||||
size_t quads = JS_ArrayLength(js,argv[0]);
|
||||
size_t verts = quads*4;
|
||||
size_t count = quads*6;
|
||||
|
||||
HMM_Vec2 *posdata = malloc(sizeof(*posdata)*verts);
|
||||
HMM_Vec2 *uvdata = malloc(sizeof(*uvdata)*verts);
|
||||
HMM_Vec4 *colordata = malloc(sizeof(*colordata)*verts);
|
||||
|
||||
for (int i = 0; i < quads; i++) {
|
||||
JSValue sub = JS_GetPropertyUint32(js,sprites,i);
|
||||
JSValue jstransform = JS_GetPropertyStr(js,sub,"transform");
|
||||
|
||||
JSValue jssrc = JS_GetPropertyStr(js,sub,"src");
|
||||
JSValue jscolor = JS_GetPropertyStr(js,sub,"color");
|
||||
HMM_Vec4 color;
|
||||
|
||||
rect src;
|
||||
if (JS_IsNull(jssrc))
|
||||
src = (rect){.x = 0, .y = 0, .w = 1, .h = 1};
|
||||
else
|
||||
src = js2rect(js,jssrc);
|
||||
|
||||
if (JS_IsNull(jscolor))
|
||||
color = (HMM_Vec4){1,1,1,1};
|
||||
else
|
||||
color = js2vec4(js,jscolor);
|
||||
|
||||
// Calculate the base index for the current quad
|
||||
size_t base = i * 4;
|
||||
|
||||
// Define the UV coordinates based on the source rectangle
|
||||
uvdata[base + 0] = (HMM_Vec2){ src.x, src.y + src.h };
|
||||
uvdata[base + 1] = (HMM_Vec2){ src.x + src.w, src.y + src.h };
|
||||
uvdata[base + 2] = (HMM_Vec2){ src.x, src.y };
|
||||
uvdata[base + 3] = (HMM_Vec2){ src.x + src.w, src.y };
|
||||
|
||||
colordata[base] = color;
|
||||
colordata[base+1] = color;
|
||||
colordata[base+2] = color;
|
||||
colordata[base+3] = color;
|
||||
|
||||
JS_FreeValue(js,jstransform);
|
||||
JS_FreeValue(js,sub);
|
||||
JS_FreeValue(js,jscolor);
|
||||
JS_FreeValue(js,jssrc);
|
||||
}
|
||||
|
||||
ret = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, ret, "pos", make_gpu_buffer(js, posdata, sizeof(*posdata) * verts, JS_TYPED_ARRAY_FLOAT32, 2, 0,0));
|
||||
JS_SetPropertyStr(js, ret, "uv", make_gpu_buffer(js, uvdata, sizeof(*uvdata) * verts, JS_TYPED_ARRAY_FLOAT32, 2, 0,0));
|
||||
JS_SetPropertyStr(js, ret, "color", make_gpu_buffer(js, colordata, sizeof(*colordata) * verts, JS_TYPED_ARRAY_FLOAT32, 4, 0,0));
|
||||
JS_SetPropertyStr(js, ret, "indices", make_quad_indices_buffer(js, quads));
|
||||
JS_SetPropertyStr(js, ret, "vertices", number2js(js, verts));
|
||||
JS_SetPropertyStr(js, ret, "count", number2js(js, count));
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_renderer_funcs[] = {
|
||||
JS_CFUNC_DEF("clear", 0, js_renderer_clear),
|
||||
JS_CFUNC_DEF("present", 0, js_renderer_present),
|
||||
JS_CFUNC_DEF("draw_color", 1, js_renderer_draw_color),
|
||||
JS_CFUNC_DEF("rect", 2, js_renderer_rect),
|
||||
JS_CFUNC_DEF("fillrect", 2, js_renderer_fillrect),
|
||||
JS_CFUNC_DEF("line", 2, js_renderer_line),
|
||||
JS_CFUNC_DEF("point", 2, js_renderer_point),
|
||||
JS_CFUNC_DEF("load_texture", 1, js_renderer_load_texture),
|
||||
JS_CFUNC_DEF("texture", 4, js_renderer_texture),
|
||||
JS_CFUNC_DEF("slice9", 4, js_renderer_slice9),
|
||||
JS_CFUNC_DEF("tile", 4, js_renderer_tile),
|
||||
JS_CFUNC_DEF("get_image", 1, js_renderer_get_image),
|
||||
JS_CFUNC_DEF("fasttext", 2, js_renderer_fasttext),
|
||||
JS_CFUNC_DEF("geometry", 2, js_renderer_geometry),
|
||||
JS_CFUNC_DEF("scale", 1, js_renderer_scale),
|
||||
JS_CFUNC_DEF("logical_size", 1, js_renderer_logical_size),
|
||||
JS_CFUNC_DEF("viewport", 1, js_renderer_viewport),
|
||||
JS_CFUNC_DEF("clip", 1, js_renderer_clip),
|
||||
JS_CFUNC_DEF("vsync", 1, js_renderer_vsync),
|
||||
JS_CFUNC_DEF("coords", 1, js_renderer_coords),
|
||||
JS_CFUNC_DEF("camera", 2, js_renderer_camera),
|
||||
JS_CFUNC_DEF("get_viewport", 0, js_renderer_get_viewport),
|
||||
JS_CFUNC_DEF("screen2world", 1, js_renderer_screen2world),
|
||||
JS_CFUNC_DEF("target", 1, js_renderer_target),
|
||||
JS_CFUNC_DEF("make_sprite_mesh",2, js_renderer_make_sprite_mesh),
|
||||
};
|
||||
|
||||
JSC_CCALL(mod_create,
|
||||
SDL_Window *win = js2SDL_Window(js,self);
|
||||
SDL_PropertiesID props = SDL_CreateProperties();
|
||||
SDL_SetNumberProperty(props, SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_NUMBER, 0);
|
||||
SDL_SetPointerProperty(props, SDL_PROP_RENDERER_CREATE_WINDOW_POINTER, win);
|
||||
SDL_SetStringProperty(props, SDL_PROP_RENDERER_CREATE_NAME_STRING, str);
|
||||
SDL_Renderer *r = SDL_CreateRendererWithProperties(props);
|
||||
SDL_DestroyProperties(props);
|
||||
if (!r) return JS_ThrowReferenceError(js, "Error creating renderer: %s",SDL_GetError());
|
||||
SDL_SetRenderDrawBlendMode(r, SDL_BLENDMODE_BLEND);
|
||||
return SDL_Renderer2js(js,r);
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_mod_funcs[] = {
|
||||
JS_CFUNC_DEF("create", 1, js_mod_create)
|
||||
};
|
||||
|
||||
JSValue js_renderer_use(JSContext *ctx) {
|
||||
// Create an object that will hold all the "renderer" methods
|
||||
JSValue obj = JS_NewObject(ctx);
|
||||
|
||||
// Add all the above C functions as properties of that object
|
||||
JS_SetPropertyFunctionList(ctx, obj,
|
||||
js_renderer_funcs,
|
||||
sizeof(js_renderer_funcs)/sizeof(JSCFunctionListEntry));
|
||||
return obj;
|
||||
}
|
||||
291
source/qjs_sdl.c
291
source/qjs_sdl.c
@@ -1,291 +0,0 @@
|
||||
#include "qjs_sdl.h"
|
||||
#include "jsffi.h"
|
||||
#include "qjs_macros.h"
|
||||
#include "cell.h"
|
||||
#include "stb_ds.h"
|
||||
#include "qjs_actor.h"
|
||||
#include "qjs_sdl_surface.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
// SDL Free functions
|
||||
void SDL_Camera_free(JSRuntime *rt, SDL_Camera *cam)
|
||||
{
|
||||
SDL_CloseCamera(cam);
|
||||
}
|
||||
|
||||
// Class definitions for SDL types
|
||||
QJSCLASS(SDL_Camera,)
|
||||
|
||||
|
||||
// CAMERA FUNCTIONS
|
||||
|
||||
// Pixel format enum conversion using the new system
|
||||
ENUM_MAPPING_TABLE(SDL_PixelFormat) = {
|
||||
{SDL_PIXELFORMAT_UNKNOWN, "unknown"},
|
||||
{SDL_PIXELFORMAT_INDEX1LSB, "index1lsb"},
|
||||
{SDL_PIXELFORMAT_INDEX1MSB, "index1msb"},
|
||||
{SDL_PIXELFORMAT_INDEX2LSB, "index2lsb"},
|
||||
{SDL_PIXELFORMAT_INDEX2MSB, "index2msb"},
|
||||
{SDL_PIXELFORMAT_INDEX4LSB, "index4lsb"},
|
||||
{SDL_PIXELFORMAT_INDEX4MSB, "index4msb"},
|
||||
{SDL_PIXELFORMAT_INDEX8, "index8"},
|
||||
{SDL_PIXELFORMAT_RGB332, "rgb332"},
|
||||
{SDL_PIXELFORMAT_XRGB4444, "xrgb4444"},
|
||||
{SDL_PIXELFORMAT_XBGR4444, "xbgr4444"},
|
||||
{SDL_PIXELFORMAT_XRGB1555, "xrgb1555"},
|
||||
{SDL_PIXELFORMAT_XBGR1555, "xbgr1555"},
|
||||
{SDL_PIXELFORMAT_ARGB4444, "argb4444"},
|
||||
{SDL_PIXELFORMAT_RGBA4444, "rgba4444"},
|
||||
{SDL_PIXELFORMAT_ABGR4444, "abgr4444"},
|
||||
{SDL_PIXELFORMAT_BGRA4444, "bgra4444"},
|
||||
{SDL_PIXELFORMAT_ARGB1555, "argb1555"},
|
||||
{SDL_PIXELFORMAT_RGBA5551, "rgba5551"},
|
||||
{SDL_PIXELFORMAT_ABGR1555, "abgr1555"},
|
||||
{SDL_PIXELFORMAT_BGRA5551, "bgra5551"},
|
||||
{SDL_PIXELFORMAT_RGB565, "rgb565"},
|
||||
{SDL_PIXELFORMAT_BGR565, "bgr565"},
|
||||
{SDL_PIXELFORMAT_RGB24, "rgb24"},
|
||||
{SDL_PIXELFORMAT_BGR24, "bgr24"},
|
||||
{SDL_PIXELFORMAT_XRGB8888, "xrgb8888"},
|
||||
{SDL_PIXELFORMAT_RGBX8888, "rgbx8888"},
|
||||
{SDL_PIXELFORMAT_XBGR8888, "xbgr8888"},
|
||||
{SDL_PIXELFORMAT_BGRX8888, "bgrx8888"},
|
||||
{SDL_PIXELFORMAT_ARGB8888, "argb8888"},
|
||||
{SDL_PIXELFORMAT_RGBA8888, "rgba8888"},
|
||||
{SDL_PIXELFORMAT_ABGR8888, "abgr8888"},
|
||||
{SDL_PIXELFORMAT_BGRA8888, "bgra8888"},
|
||||
{SDL_PIXELFORMAT_XRGB2101010, "xrgb2101010"},
|
||||
{SDL_PIXELFORMAT_XBGR2101010, "xbgr2101010"},
|
||||
{SDL_PIXELFORMAT_ARGB2101010, "argb2101010"},
|
||||
{SDL_PIXELFORMAT_ABGR2101010, "abgr2101010"},
|
||||
{SDL_PIXELFORMAT_RGB48, "rgb48"},
|
||||
{SDL_PIXELFORMAT_BGR48, "bgr48"},
|
||||
{SDL_PIXELFORMAT_RGBA64, "rgba64"},
|
||||
{SDL_PIXELFORMAT_ARGB64, "argb64"},
|
||||
{SDL_PIXELFORMAT_BGRA64, "bgra64"},
|
||||
{SDL_PIXELFORMAT_ABGR64, "abgr64"},
|
||||
{SDL_PIXELFORMAT_RGB48_FLOAT, "rgb48_float"},
|
||||
{SDL_PIXELFORMAT_BGR48_FLOAT, "bgr48_float"},
|
||||
{SDL_PIXELFORMAT_RGBA64_FLOAT, "rgba64_float"},
|
||||
{SDL_PIXELFORMAT_ARGB64_FLOAT, "argb64_float"},
|
||||
{SDL_PIXELFORMAT_BGRA64_FLOAT, "bgra64_float"},
|
||||
{SDL_PIXELFORMAT_ABGR64_FLOAT, "abgr64_float"},
|
||||
{SDL_PIXELFORMAT_RGB96_FLOAT, "rgb96_float"},
|
||||
{SDL_PIXELFORMAT_BGR96_FLOAT, "bgr96_float"},
|
||||
{SDL_PIXELFORMAT_RGBA128_FLOAT, "rgba128_float"},
|
||||
{SDL_PIXELFORMAT_ARGB128_FLOAT, "argb128_float"},
|
||||
{SDL_PIXELFORMAT_BGRA128_FLOAT, "bgra128_float"},
|
||||
{SDL_PIXELFORMAT_ABGR128_FLOAT, "abgr128_float"},
|
||||
{SDL_PIXELFORMAT_YV12, "yv12"},
|
||||
{SDL_PIXELFORMAT_IYUV, "iyuv"},
|
||||
{SDL_PIXELFORMAT_YUY2, "yuy2"},
|
||||
{SDL_PIXELFORMAT_UYVY, "uyvy"},
|
||||
{SDL_PIXELFORMAT_YVYU, "yvyu"},
|
||||
{SDL_PIXELFORMAT_NV12, "nv12"},
|
||||
{SDL_PIXELFORMAT_NV21, "nv21"},
|
||||
{SDL_PIXELFORMAT_P010, "p010"},
|
||||
{SDL_PIXELFORMAT_RGBA32, "rgba32"}
|
||||
};
|
||||
JS2ENUM(SDL_PixelFormat)
|
||||
|
||||
static JSValue cameraspec2js(JSContext *js, const SDL_CameraSpec *spec) {
|
||||
JSValue obj = JS_NewObject(js);
|
||||
|
||||
JS_SetPropertyStr(js, obj, "format", SDL_PixelFormat2js(js, spec->format));
|
||||
JS_SetPropertyStr(js, obj, "colorspace", JS_NewInt32(js, spec->colorspace));
|
||||
JS_SetPropertyStr(js, obj, "width", JS_NewInt32(js, spec->width));
|
||||
JS_SetPropertyStr(js, obj, "height", JS_NewInt32(js, spec->height));
|
||||
JS_SetPropertyStr(js, obj, "framerate_numerator", JS_NewInt32(js, spec->framerate_numerator));
|
||||
JS_SetPropertyStr(js, obj, "framerate_denominator", JS_NewInt32(js, spec->framerate_denominator));
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
static SDL_CameraSpec js2cameraspec(JSContext *js, JSValue obj) {
|
||||
SDL_CameraSpec spec = {0};
|
||||
|
||||
JSValue v;
|
||||
|
||||
v = JS_GetPropertyStr(js, obj, "format");
|
||||
if (!JS_IsNull(v)) {
|
||||
spec.format = js2SDL_PixelFormat(js, v);
|
||||
}
|
||||
JS_FreeValue(js, v);
|
||||
|
||||
v = JS_GetPropertyStr(js, obj, "colorspace");
|
||||
if (!JS_IsNull(v)) JS_ToInt32(js, &spec.colorspace, v);
|
||||
JS_FreeValue(js, v);
|
||||
|
||||
v = JS_GetPropertyStr(js, obj, "width");
|
||||
if (!JS_IsNull(v)) JS_ToInt32(js, &spec.width, v);
|
||||
JS_FreeValue(js, v);
|
||||
|
||||
v = JS_GetPropertyStr(js, obj, "height");
|
||||
if (!JS_IsNull(v)) JS_ToInt32(js, &spec.height, v);
|
||||
JS_FreeValue(js, v);
|
||||
|
||||
v = JS_GetPropertyStr(js, obj, "framerate_numerator");
|
||||
if (!JS_IsNull(v)) JS_ToInt32(js, &spec.framerate_numerator, v);
|
||||
JS_FreeValue(js, v);
|
||||
|
||||
v = JS_GetPropertyStr(js, obj, "framerate_denominator");
|
||||
if (!JS_IsNull(v)) JS_ToInt32(js, &spec.framerate_denominator, v);
|
||||
JS_FreeValue(js, v);
|
||||
|
||||
return spec;
|
||||
}
|
||||
|
||||
JSC_CCALL(camera_list,
|
||||
int num;
|
||||
JSValue jsids = JS_NewArray(js);
|
||||
SDL_CameraID *ids = SDL_GetCameras(&num);
|
||||
for (int i = 0; i < num; i++)
|
||||
JS_SetPropertyUint32(js,jsids, i, number2js(js,ids[i]));
|
||||
|
||||
return jsids;
|
||||
)
|
||||
|
||||
JSC_CCALL(camera_open,
|
||||
int id = js2number(js,argv[0]);
|
||||
SDL_CameraSpec *spec_ptr = NULL;
|
||||
SDL_CameraSpec spec;
|
||||
|
||||
// Check if a format spec was provided
|
||||
if (argc > 1 && !JS_IsNull(argv[1])) {
|
||||
spec = js2cameraspec(js, argv[1]);
|
||||
spec_ptr = &spec;
|
||||
}
|
||||
|
||||
SDL_Camera *cam = SDL_OpenCamera(id, spec_ptr);
|
||||
if (!cam) ret = JS_ThrowReferenceError(js, "Could not open camera %d: %s\n", id, SDL_GetError());
|
||||
else
|
||||
ret = SDL_Camera2js(js,cam);
|
||||
)
|
||||
|
||||
JSC_CCALL(camera_name,
|
||||
const char *name = SDL_GetCameraName(js2number(js,argv[0]));
|
||||
if (!name) return JS_ThrowReferenceError(js, "Could not get camera name from id %d.", (int)js2number(js,argv[0]));
|
||||
|
||||
return JS_NewString(js, name);
|
||||
)
|
||||
|
||||
JSC_CCALL(camera_position,
|
||||
SDL_CameraPosition pos = SDL_GetCameraPosition(js2number(js,argv[0]));
|
||||
switch(pos) {
|
||||
case SDL_CAMERA_POSITION_UNKNOWN: return JS_NewString(js,"unknown");
|
||||
case SDL_CAMERA_POSITION_FRONT_FACING: return JS_NewString(js,"front");
|
||||
case SDL_CAMERA_POSITION_BACK_FACING: return JS_NewString(js,"back");
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(camera_drivers,
|
||||
int num = SDL_GetNumCameraDrivers();
|
||||
JSValue arr = JS_NewArray(js);
|
||||
for (int i = 0; i < num; i++)
|
||||
JS_SetPropertyUint32(js, arr, i, JS_NewString(js, SDL_GetCameraDriver(i)));
|
||||
return arr;
|
||||
)
|
||||
|
||||
JSC_CCALL(camera_supported_formats,
|
||||
SDL_CameraID id = js2number(js,argv[0]);
|
||||
int num;
|
||||
SDL_CameraSpec **specs = SDL_GetCameraSupportedFormats(id, &num);
|
||||
|
||||
if (!specs)
|
||||
return JS_ThrowReferenceError(js, "Could not get supported formats for camera %d: %s", id, SDL_GetError());
|
||||
|
||||
JSValue arr = JS_NewArray(js);
|
||||
for (int i = 0; i < num; i++) {
|
||||
JS_SetPropertyUint32(js, arr, i, cameraspec2js(js, specs[i]));
|
||||
}
|
||||
|
||||
SDL_free(specs);
|
||||
return arr;
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_camera_funcs[] = {
|
||||
MIST_FUNC_DEF(camera, list, 0),
|
||||
MIST_FUNC_DEF(camera, open, 2),
|
||||
MIST_FUNC_DEF(camera, name, 1),
|
||||
MIST_FUNC_DEF(camera, position, 1),
|
||||
MIST_FUNC_DEF(camera, drivers, 0),
|
||||
MIST_FUNC_DEF(camera, supported_formats, 1),
|
||||
};
|
||||
|
||||
JSC_CCALL(camera_capture,
|
||||
SDL_ClearError();
|
||||
SDL_Camera *cam = js2SDL_Camera(js,self);
|
||||
if (!cam) return JS_ThrowReferenceError(js,"Self was not a camera: %s", SDL_GetError());
|
||||
|
||||
SDL_Surface *surf = SDL_AcquireCameraFrame(cam, NULL);
|
||||
if (!surf) {
|
||||
const char *msg = SDL_GetError();
|
||||
if (msg[0] != 0)
|
||||
return JS_ThrowReferenceError(js,"Could not get camera frame: %s", SDL_GetError());
|
||||
else return JS_NULL;
|
||||
}
|
||||
|
||||
// Create a copy of the surface
|
||||
SDL_Surface *newsurf = SDL_CreateSurface(surf->w, surf->h, surf->format);
|
||||
|
||||
if (!newsurf) {
|
||||
SDL_ReleaseCameraFrame(cam, surf);
|
||||
return JS_ThrowReferenceError(js, "Could not create surface: %s", SDL_GetError());
|
||||
}
|
||||
|
||||
// Copy the surface data
|
||||
int result = SDL_BlitSurface(surf, NULL, newsurf, NULL);
|
||||
|
||||
// Release the camera frame
|
||||
SDL_ReleaseCameraFrame(cam, surf);
|
||||
|
||||
if (result != 0) {
|
||||
SDL_DestroySurface(newsurf);
|
||||
return JS_ThrowReferenceError(js, "Could not blit surface: %s", SDL_GetError());
|
||||
}
|
||||
|
||||
return SDL_Surface2js(js,newsurf);
|
||||
)
|
||||
|
||||
JSC_CCALL(camera_get_driver,
|
||||
SDL_Camera *cam = js2SDL_Camera(js,self);
|
||||
if (!cam) return JS_ThrowReferenceError(js,"Self was not a camera: %s", SDL_GetError());
|
||||
|
||||
const char *driver = SDL_GetCurrentCameraDriver();
|
||||
if (!driver) return JS_NULL;
|
||||
|
||||
return JS_NewString(js, driver);
|
||||
)
|
||||
|
||||
JSC_CCALL(camera_get_format,
|
||||
SDL_Camera *cam = js2SDL_Camera(js,self);
|
||||
if (!cam) return JS_ThrowReferenceError(js,"Self was not a camera: %s", SDL_GetError());
|
||||
|
||||
SDL_CameraSpec spec;
|
||||
if (!SDL_GetCameraFormat(cam, &spec))
|
||||
return JS_ThrowReferenceError(js, "Could not get camera format: %s", SDL_GetError());
|
||||
|
||||
return cameraspec2js(js, &spec);
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_SDL_Camera_funcs[] =
|
||||
{
|
||||
MIST_FUNC_DEF(camera, capture, 0),
|
||||
MIST_FUNC_DEF(camera, get_driver, 0),
|
||||
MIST_FUNC_DEF(camera, get_format, 0),
|
||||
};
|
||||
|
||||
JSValue js_camera_use(JSContext *js) {
|
||||
SDL_Init(SDL_INIT_CAMERA);
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js,mod,js_camera_funcs,countof(js_camera_funcs));
|
||||
QJSCLASSPREP_FUNCS(SDL_Camera)
|
||||
return mod;
|
||||
}
|
||||
|
||||
JSValue js_sdl_use(JSContext *js) {
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, mod, "camera", js_camera_use(js));
|
||||
return mod;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
#ifndef QJS_SDL_H
|
||||
#define QJS_SDL_H
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include "cell.h"
|
||||
|
||||
JSValue js_input_use(JSContext *ctx);
|
||||
JSValue js_camera_use(JSContext *ctx);
|
||||
JSValue js_sdl_audio_use(JSContext *ctx);
|
||||
JSValue js_sdl_use(JSContext *js);
|
||||
|
||||
SDL_PixelFormat str2pixelformat(const char *str);
|
||||
SDL_PixelFormat js2pixelformat(JSContext *js, JSValue v);
|
||||
JSValue pixelformat2js(JSContext *js, SDL_PixelFormat format);
|
||||
const char *pixelformat2str(SDL_PixelFormat format);
|
||||
|
||||
// New enum system functions
|
||||
int js2SDL_PixelFormat(JSContext *js, JSValue v);
|
||||
JSValue SDL_PixelFormat2js(JSContext *js, int enumval);
|
||||
SDL_Colorspace str2colorspace(const char *str);
|
||||
SDL_Colorspace js2colorspace(JSContext *js, JSValue v);
|
||||
JSValue colorspace2js(JSContext *js, SDL_Colorspace colorspace);
|
||||
const char *colorspace2str(SDL_Colorspace colorspace);
|
||||
|
||||
// SDL Scale Mode functions
|
||||
SDL_ScaleMode js2SDL_ScaleMode(JSContext *js, JSValue v);
|
||||
JSValue SDL_ScaleMode2js(JSContext *js, SDL_ScaleMode mode);
|
||||
|
||||
// Surface type
|
||||
typedef struct SDL_Surface SDL_Surface;
|
||||
SDL_Surface *js2SDL_Surface(JSContext *js, JSValue v);
|
||||
JSValue SDL_Surface2js(JSContext *js, SDL_Surface *s);
|
||||
|
||||
#endif /* QJS_SDL_H */
|
||||
@@ -1,372 +0,0 @@
|
||||
#include "qjs_macros.h"
|
||||
#include "jsffi.h"
|
||||
#include "quickjs.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3/SDL_audio.h>
|
||||
#include "cell.h"
|
||||
|
||||
#define countof(x) (sizeof(x)/sizeof((x)[0]))
|
||||
|
||||
// Helper functions
|
||||
double js2number(JSContext *js, JSValue v);
|
||||
int js2bool(JSContext *js, JSValue v);
|
||||
|
||||
// Free functions for finalizers
|
||||
void SDL_AudioStream_free(JSRuntime *rt, SDL_AudioStream *stream) {
|
||||
SDL_DestroyAudioStream(stream);
|
||||
}
|
||||
|
||||
// Class definitions
|
||||
QJSCLASS(SDL_AudioStream,)
|
||||
|
||||
// Conversion functions
|
||||
SDL_AudioFormat js2SDL_AudioFormat(JSContext *js, JSValue v) {
|
||||
int fmt = js2number(js, v);
|
||||
return (SDL_AudioFormat)fmt;
|
||||
}
|
||||
|
||||
JSValue SDL_AudioFormat2js(JSContext *js, SDL_AudioFormat fmt) {
|
||||
return JS_NewInt32(js, (int)fmt);
|
||||
}
|
||||
|
||||
SDL_AudioDeviceID js2SDL_AudioDeviceID(JSContext *js, JSValue v) {
|
||||
return (SDL_AudioDeviceID)js2number(js, v);
|
||||
}
|
||||
|
||||
JSValue SDL_AudioDeviceID2js(JSContext *js, SDL_AudioDeviceID id) {
|
||||
return JS_NewInt32(js, (int)id);
|
||||
}
|
||||
|
||||
SDL_AudioSpec js2SDL_AudioSpec(JSContext *js, JSValue v) {
|
||||
SDL_AudioSpec spec = {0};
|
||||
JS_GETPROP(js, spec.format, v, format, SDL_AudioFormat)
|
||||
JS_GETPROP(js, spec.channels, v, channels, number)
|
||||
JS_GETPROP(js, spec.freq, v, freq, number)
|
||||
return spec;
|
||||
}
|
||||
|
||||
JSValue SDL_AudioSpec2js(JSContext *js, SDL_AudioSpec spec) {
|
||||
JSValue obj = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, obj, "format", SDL_AudioFormat2js(js, spec.format));
|
||||
JS_SetPropertyStr(js, obj, "channels", JS_NewInt32(js, spec.channels));
|
||||
JS_SetPropertyStr(js, obj, "freq", JS_NewInt32(js, spec.freq));
|
||||
return obj;
|
||||
}
|
||||
|
||||
// Enum mappings for audio formats (simplified)
|
||||
JSValue js_get_audio_drivers(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
int count = SDL_GetNumAudioDrivers();
|
||||
JSValue arr = JS_NewArray(js);
|
||||
for (int i = 0; i < count; i++) {
|
||||
const char *driver = SDL_GetAudioDriver(i);
|
||||
JS_SetPropertyUint32(js, arr, i, JS_NewString(js, driver));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
JSValue js_get_current_audio_driver(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
const char *driver = SDL_GetCurrentAudioDriver();
|
||||
return driver ? JS_NewString(js, driver) : JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_get_audio_playback_devices(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioDeviceID *devices = SDL_GetAudioPlaybackDevices(NULL);
|
||||
if (!devices) return JS_NULL;
|
||||
JSValue arr = JS_NewArray(js);
|
||||
for (int i = 0; devices[i]; i++) {
|
||||
JS_SetPropertyUint32(js, arr, i, SDL_AudioDeviceID2js(js, devices[i]));
|
||||
}
|
||||
SDL_free(devices);
|
||||
return arr;
|
||||
}
|
||||
|
||||
JSValue js_get_audio_recording_devices(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioDeviceID *devices = SDL_GetAudioRecordingDevices(NULL);
|
||||
if (!devices) return JS_NULL;
|
||||
JSValue arr = JS_NewArray(js);
|
||||
for (int i = 0; devices[i]; i++) {
|
||||
JS_SetPropertyUint32(js, arr, i, SDL_AudioDeviceID2js(js, devices[i]));
|
||||
}
|
||||
SDL_free(devices);
|
||||
return arr;
|
||||
}
|
||||
|
||||
JSValue js_get_audio_device_name(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
const char *name = SDL_GetAudioDeviceName(devid);
|
||||
return name ? JS_NewString(js, name) : JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_is_audio_device_playback(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
return JS_NewBool(js, SDL_IsAudioDevicePlayback(devid));
|
||||
}
|
||||
|
||||
JSValue js_is_audio_device_physical(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
return JS_NewBool(js, SDL_IsAudioDevicePhysical(devid));
|
||||
}
|
||||
|
||||
JSValue js_get_audio_device_format(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
SDL_AudioSpec spec;
|
||||
if (!SDL_GetAudioDeviceFormat(devid, &spec, NULL)) {
|
||||
return JS_NULL;
|
||||
}
|
||||
return SDL_AudioSpec2js(js, spec);
|
||||
}
|
||||
|
||||
JSValue js_open_audio_device_stream(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
SDL_AudioSpec spec = {0};
|
||||
if (argc > 1) {
|
||||
spec = js2SDL_AudioSpec(js, argv[1]);
|
||||
}
|
||||
SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(devid, &spec, NULL, NULL);
|
||||
if (!stream) {
|
||||
return JS_ThrowInternalError(js, "Failed to open audio device stream: %s", SDL_GetError());
|
||||
}
|
||||
return SDL_AudioStream2js(js, stream);
|
||||
}
|
||||
|
||||
JSValue js_create_audio_stream(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
SDL_AudioSpec src_spec = js2SDL_AudioSpec(js, argv[0]);
|
||||
SDL_AudioSpec dst_spec = js2SDL_AudioSpec(js, argv[1]);
|
||||
SDL_AudioStream *stream = SDL_CreateAudioStream(&src_spec, &dst_spec);
|
||||
if (!stream) {
|
||||
return JS_ThrowInternalError(js, "Failed to create audio stream: %s", SDL_GetError());
|
||||
}
|
||||
return SDL_AudioStream2js(js, stream);
|
||||
}
|
||||
|
||||
JSC_CCALL(audio_stream_put_data,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
size_t len;
|
||||
void *data = js_get_blob_data(js, &len, argv[0]);
|
||||
if (!SDL_PutAudioStreamData(stream, data, len)) {
|
||||
ret = JS_ThrowInternalError(js, "Failed to put audio stream data: %s", SDL_GetError());
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_get_data,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
int len = js2number(js, argv[0]);
|
||||
void *data = malloc(len);
|
||||
int got = SDL_GetAudioStreamData(stream, data, len);
|
||||
if (got < 0) {
|
||||
free(data);
|
||||
ret = JS_ThrowInternalError(js, "Failed to get audio stream data: %s", SDL_GetError());
|
||||
} else {
|
||||
ret = js_new_blob_stoned_copy(js, data, got);
|
||||
free(data);
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_available,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
ret = JS_NewInt32(js, SDL_GetAudioStreamAvailable(stream));
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_queued,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
ret = JS_NewInt32(js, SDL_GetAudioStreamQueued(stream));
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_flush,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_FlushAudioStream(stream);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_clear,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_ClearAudioStream(stream);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_bind,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
if (!SDL_BindAudioStream(devid, stream)) {
|
||||
ret = JS_ThrowInternalError(js, "Failed to bind audio stream: %s", SDL_GetError());
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_unbind,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_UnbindAudioStream(stream);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_get_format,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_AudioSpec src, dst;
|
||||
if (!SDL_GetAudioStreamFormat(stream, &src, &dst)) {
|
||||
ret = JS_NULL;
|
||||
} else {
|
||||
JSValue obj = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, obj, "src", SDL_AudioSpec2js(js, src));
|
||||
JS_SetPropertyStr(js, obj, "dst", SDL_AudioSpec2js(js, dst));
|
||||
ret = obj;
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_get_device,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_AudioDeviceID devid = SDL_GetAudioStreamDevice(stream);
|
||||
ret = SDL_AudioDeviceID2js(js, devid);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_get_gain,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
ret = JS_NewFloat64(js, SDL_GetAudioStreamGain(stream));
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_set_gain,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
float gain = js2number(js, argv[0]);
|
||||
if (!SDL_SetAudioStreamGain(stream, gain)) {
|
||||
ret = JS_ThrowInternalError(js, "Failed to set audio stream gain: %s", SDL_GetError());
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_set_frequency_ratio,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
float ratio = js2number(js, argv[0]);
|
||||
if (!SDL_SetAudioStreamFrequencyRatio(stream, ratio)) {
|
||||
ret = JS_ThrowInternalError(js, "Failed to set audio stream frequency ratio: %s", SDL_GetError());
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_get_frequency_ratio,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
ret = JS_NewFloat64(js, SDL_GetAudioStreamFrequencyRatio(stream));
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_device_pause,
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
SDL_PauseAudioDevice(devid);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_device_resume,
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
SDL_ResumeAudioDevice(devid);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_device_paused,
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
ret = JS_NewBool(js, SDL_AudioDevicePaused(devid));
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_device_paused,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
ret = JS_NewBool(js, SDL_AudioStreamDevicePaused(stream));
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_pause_device,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_PauseAudioStreamDevice(stream);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_stream_resume_device,
|
||||
SDL_AudioStream *stream = js2SDL_AudioStream(js, self);
|
||||
SDL_ResumeAudioStreamDevice(stream);
|
||||
)
|
||||
|
||||
JSC_CCALL(audio_device_close,
|
||||
SDL_AudioDeviceID devid = js2SDL_AudioDeviceID(js, argv[0]);
|
||||
SDL_CloseAudioDevice(devid);
|
||||
)
|
||||
|
||||
JSValue js_load_wav(JSContext *js, JSValue self, int argc, JSValue *argv) {
|
||||
const char *path = JS_ToCString(js, argv[0]);
|
||||
SDL_AudioSpec spec;
|
||||
Uint8 *data;
|
||||
Uint32 len;
|
||||
if (!SDL_LoadWAV(path, &spec, &data, &len)) {
|
||||
JS_FreeCString(js, path);
|
||||
return JS_ThrowInternalError(js, "Failed to load WAV: %s", SDL_GetError());
|
||||
}
|
||||
JS_FreeCString(js, path);
|
||||
|
||||
JSValue obj = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, obj, "spec", SDL_AudioSpec2js(js, spec));
|
||||
JS_SetPropertyStr(js, obj, "data", js_new_blob_stoned_copy(js, data, len));
|
||||
SDL_free(data);
|
||||
return obj;
|
||||
}
|
||||
|
||||
JSC_CCALL(convert_audio_samples,
|
||||
SDL_AudioSpec src_spec = js2SDL_AudioSpec(js, argv[0]);
|
||||
SDL_AudioSpec dst_spec = js2SDL_AudioSpec(js, argv[1]);
|
||||
size_t src_len;
|
||||
void *src_data = js_get_blob_data(js, &src_len, argv[2]);
|
||||
Uint8 *dst_data = NULL;
|
||||
int dst_len = 0;
|
||||
if (!SDL_ConvertAudioSamples(&src_spec, src_data, (int)src_len, &dst_spec, &dst_data, &dst_len)) {
|
||||
ret = JS_ThrowInternalError(js, "Failed to convert audio samples: %s", SDL_GetError());
|
||||
} else {
|
||||
ret = js_new_blob_stoned_copy(js, dst_data, dst_len);
|
||||
SDL_free(dst_data);
|
||||
}
|
||||
)
|
||||
|
||||
JSC_CCALL(mix_audio,
|
||||
SDL_AudioFormat format = js2SDL_AudioFormat(js, argv[0]);
|
||||
size_t len;
|
||||
void *dst = js_get_blob_data(js, &len, argv[1]);
|
||||
void *src = js_get_blob_data(js, &len, argv[2]);
|
||||
float volume = js2number(js, argv[3]);
|
||||
SDL_MixAudio(dst, src, format, len, volume);
|
||||
)
|
||||
|
||||
// Function list for SDL_AudioStream
|
||||
static const JSCFunctionListEntry js_SDL_AudioStream_funcs[] = {
|
||||
JS_CFUNC_DEF("put", 1, js_audio_stream_put_data),
|
||||
JS_CFUNC_DEF("get", 1, js_audio_stream_get_data),
|
||||
JS_CFUNC_DEF("available", 0, js_audio_stream_available),
|
||||
JS_CFUNC_DEF("queued", 0, js_audio_stream_queued),
|
||||
JS_CFUNC_DEF("flush", 0, js_audio_stream_flush),
|
||||
JS_CFUNC_DEF("clear", 0, js_audio_stream_clear),
|
||||
JS_CFUNC_DEF("bind", 1, js_audio_stream_bind),
|
||||
JS_CFUNC_DEF("unbind", 0, js_audio_stream_unbind),
|
||||
JS_CFUNC_DEF("get_format", 0, js_audio_stream_get_format),
|
||||
JS_CFUNC_DEF("get_device", 0, js_audio_stream_get_device),
|
||||
JS_CGETSET_DEF("gain", js_audio_stream_get_gain, js_audio_stream_set_gain),
|
||||
JS_CGETSET_DEF("frequency_ratio", js_audio_stream_get_frequency_ratio, js_audio_stream_set_frequency_ratio),
|
||||
JS_CFUNC_DEF("pause_device", 0, js_audio_stream_pause_device),
|
||||
JS_CFUNC_DEF("resume_device", 0, js_audio_stream_resume_device),
|
||||
JS_CFUNC_DEF("device_paused", 0, js_audio_stream_device_paused),
|
||||
};
|
||||
|
||||
// Main function list
|
||||
static const JSCFunctionListEntry js_sdl_audio_funcs[] = {
|
||||
JS_CFUNC_DEF("get_drivers", 0, js_get_audio_drivers),
|
||||
JS_CFUNC_DEF("get_current_driver", 0, js_get_current_audio_driver),
|
||||
JS_CFUNC_DEF("get_playback_devices", 0, js_get_audio_playback_devices),
|
||||
JS_CFUNC_DEF("get_recording_devices", 0, js_get_audio_recording_devices),
|
||||
JS_CFUNC_DEF("get_device_name", 1, js_get_audio_device_name),
|
||||
JS_CFUNC_DEF("is_playback_device", 1, js_is_audio_device_playback),
|
||||
JS_CFUNC_DEF("is_physical_device", 1, js_is_audio_device_physical),
|
||||
JS_CFUNC_DEF("get_device_format", 1, js_get_audio_device_format),
|
||||
JS_CFUNC_DEF("open_device_stream", 1, js_open_audio_device_stream),
|
||||
JS_CFUNC_DEF("create_stream", 2, js_create_audio_stream),
|
||||
JS_CFUNC_DEF("pause_device", 1, js_audio_device_pause),
|
||||
JS_CFUNC_DEF("resume_device", 1, js_audio_device_resume),
|
||||
JS_CFUNC_DEF("device_paused", 1, js_audio_device_paused),
|
||||
JS_CFUNC_DEF("close_device", 1, js_audio_device_close),
|
||||
JS_CFUNC_DEF("load_wav", 1, js_load_wav),
|
||||
JS_CFUNC_DEF("convert_samples", 3, js_convert_audio_samples),
|
||||
JS_CFUNC_DEF("mix_audio", 4, js_mix_audio),
|
||||
};
|
||||
|
||||
// Use function
|
||||
JSValue js_sdl_audio_use(JSContext *js) {
|
||||
JS_NewClassID(&js_SDL_AudioStream_id);
|
||||
JS_NewClass(JS_GetRuntime(js), js_SDL_AudioStream_id, &js_SDL_AudioStream_class);
|
||||
JSValue proto = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, proto, js_SDL_AudioStream_funcs, countof(js_SDL_AudioStream_funcs));
|
||||
JS_SetClassProto(js, js_SDL_AudioStream_id, proto);
|
||||
|
||||
JSValue export = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, export, js_sdl_audio_funcs, countof(js_sdl_audio_funcs));
|
||||
return export;
|
||||
}
|
||||
1704
source/qjs_sdl_gpu.c
1704
source/qjs_sdl_gpu.c
File diff suppressed because it is too large
Load Diff
@@ -1,15 +0,0 @@
|
||||
#ifndef QJS_SDL_GPU_H
|
||||
#define QJS_SDL_GPU_H
|
||||
|
||||
#include "jsffi.h"
|
||||
#include "sprite.h"
|
||||
|
||||
// Forward declarations for sprite sorting functions
|
||||
int sort_sprite(const sprite *a, const sprite *b);
|
||||
int sort_sprite_backtofront(const sprite *a, const sprite *b);
|
||||
int sort_sprite_fronttoback(const sprite *a, const sprite *b);
|
||||
int sort_sprite_texture(const sprite *a, const sprite *b);
|
||||
|
||||
JSValue js_sdl_gpu_use(JSContext *js);
|
||||
|
||||
#endif
|
||||
@@ -1,790 +0,0 @@
|
||||
#include "qjs_sdl_input.h"
|
||||
#include "jsffi.h"
|
||||
#include "qjs_macros.h"
|
||||
#include "cell.h"
|
||||
#include "stb_ds.h"
|
||||
#include "qjs_actor.h"
|
||||
#include "qjs_wota.h"
|
||||
#include "qjs_imgui.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
// Internal keymod function for input module
|
||||
static JSValue js_keymod(JSContext *js)
|
||||
{
|
||||
SDL_Keymod modstate = SDL_GetModState();
|
||||
JSValue ret = JS_NewObject(js);
|
||||
if (SDL_KMOD_CTRL & modstate)
|
||||
JS_SetPropertyStr(js,ret,"ctrl", JS_NewBool(js,1));
|
||||
if (SDL_KMOD_SHIFT & modstate)
|
||||
JS_SetPropertyStr(js,ret,"shift", JS_NewBool(js,1));
|
||||
if (SDL_KMOD_ALT & modstate)
|
||||
JS_SetPropertyStr(js,ret,"alt", JS_NewBool(js,1));
|
||||
if (SDL_KMOD_GUI & modstate)
|
||||
JS_SetPropertyStr(js,ret,"super", JS_NewBool(js,1));
|
||||
if (SDL_KMOD_NUM & modstate)
|
||||
JS_SetPropertyStr(js,ret,"numlock", JS_NewBool(js,1));
|
||||
if (SDL_KMOD_CAPS & modstate)
|
||||
JS_SetPropertyStr(js,ret,"caps", JS_NewBool(js,1));
|
||||
if (SDL_KMOD_SCROLL & modstate)
|
||||
JS_SetPropertyStr(js,ret,"scrolllock", JS_NewBool(js,1));
|
||||
if (SDL_KMOD_MODE & modstate)
|
||||
JS_SetPropertyStr(js,ret,"mode", JS_NewBool(js,1));
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
// INPUT FUNCTIONS
|
||||
JSC_CCALL(input_mouse_lock, SDL_CaptureMouse(JS_ToBool(js,argv[0])))
|
||||
|
||||
JSC_CCALL(input_mouse_show,
|
||||
if (JS_ToBool(js,argv[0]))
|
||||
SDL_ShowCursor();
|
||||
else
|
||||
SDL_HideCursor();
|
||||
)
|
||||
|
||||
JSC_CCALL(input_keyname,
|
||||
return JS_NewString(js, SDL_GetKeyName(js2number(js,argv[0])));
|
||||
)
|
||||
|
||||
JSC_CCALL(input_keymod,
|
||||
return js_keymod(js);
|
||||
)
|
||||
|
||||
JSC_CCALL(input_mousestate,
|
||||
float x,y;
|
||||
SDL_MouseButtonFlags flags = SDL_GetMouseState(&x,&y);
|
||||
JSValue m = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js,m,"x", number2js(js,x));
|
||||
JS_SetPropertyStr(js,m,"y", number2js(js,y));
|
||||
|
||||
if (flags & SDL_BUTTON_LMASK)
|
||||
JS_SetPropertyStr(js, m, "left", JS_NewBool(js, 1));
|
||||
if (flags & SDL_BUTTON_MMASK)
|
||||
JS_SetPropertyStr(js, m, "middle", JS_NewBool(js, 1));
|
||||
if (flags & SDL_BUTTON_RMASK)
|
||||
JS_SetPropertyStr(js, m, "right", JS_NewBool(js, 1));
|
||||
if (flags & SDL_BUTTON_X1MASK)
|
||||
JS_SetPropertyStr(js, m, "x1", JS_NewBool(js, 1));
|
||||
if (flags & SDL_BUTTON_X2MASK)
|
||||
JS_SetPropertyStr(js, m, "x2", JS_NewBool(js, 1));
|
||||
|
||||
return m;
|
||||
)
|
||||
|
||||
// Event processing functions (moved from cell.c)
|
||||
|
||||
const char* event_type_to_string(Uint32 event_type) {
|
||||
switch (event_type) {
|
||||
// Application events
|
||||
case SDL_EVENT_QUIT: return "quit";
|
||||
case SDL_EVENT_TERMINATING: return "terminating";
|
||||
case SDL_EVENT_LOW_MEMORY: return "low_memory";
|
||||
case SDL_EVENT_WILL_ENTER_BACKGROUND: return "will_enter_background";
|
||||
case SDL_EVENT_DID_ENTER_BACKGROUND: return "did_enter_background";
|
||||
case SDL_EVENT_WILL_ENTER_FOREGROUND: return "will_enter_foreground";
|
||||
case SDL_EVENT_DID_ENTER_FOREGROUND: return "did_enter_foreground";
|
||||
case SDL_EVENT_LOCALE_CHANGED: return "locale_changed";
|
||||
case SDL_EVENT_SYSTEM_THEME_CHANGED: return "system_theme_changed";
|
||||
|
||||
// Display events
|
||||
case SDL_EVENT_DISPLAY_ORIENTATION: return "display_orientation";
|
||||
case SDL_EVENT_DISPLAY_ADDED: return "display_added";
|
||||
case SDL_EVENT_DISPLAY_REMOVED: return "display_removed";
|
||||
case SDL_EVENT_DISPLAY_MOVED: return "display_moved";
|
||||
case SDL_EVENT_DISPLAY_DESKTOP_MODE_CHANGED: return "display_desktop_mode_changed";
|
||||
case SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED: return "display_current_mode_changed";
|
||||
case SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED: return "display_content_scale_changed";
|
||||
|
||||
// Window events
|
||||
case SDL_EVENT_WINDOW_SHOWN: return "window_shown";
|
||||
case SDL_EVENT_WINDOW_HIDDEN: return "window_hidden";
|
||||
case SDL_EVENT_WINDOW_EXPOSED: return "window_exposed";
|
||||
case SDL_EVENT_WINDOW_MOVED: return "window_moved";
|
||||
case SDL_EVENT_WINDOW_RESIZED: return "window_resized";
|
||||
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED: return "window_pixel_size_changed";
|
||||
case SDL_EVENT_WINDOW_METAL_VIEW_RESIZED: return "window_metal_view_resized";
|
||||
case SDL_EVENT_WINDOW_MINIMIZED: return "window_minimized";
|
||||
case SDL_EVENT_WINDOW_MAXIMIZED: return "window_maximized";
|
||||
case SDL_EVENT_WINDOW_RESTORED: return "window_restored";
|
||||
case SDL_EVENT_WINDOW_MOUSE_ENTER: return "window_mouse_enter";
|
||||
case SDL_EVENT_WINDOW_MOUSE_LEAVE: return "window_mouse_leave";
|
||||
case SDL_EVENT_WINDOW_FOCUS_GAINED: return "window_focus_gained";
|
||||
case SDL_EVENT_WINDOW_FOCUS_LOST: return "window_focus_lost";
|
||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED: return "window_close_requested";
|
||||
case SDL_EVENT_WINDOW_HIT_TEST: return "window_hit_test";
|
||||
case SDL_EVENT_WINDOW_ICCPROF_CHANGED: return "window_iccprof_changed";
|
||||
case SDL_EVENT_WINDOW_DISPLAY_CHANGED: return "window_display_changed";
|
||||
case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED: return "window_display_scale_changed";
|
||||
case SDL_EVENT_WINDOW_SAFE_AREA_CHANGED: return "window_safe_area_changed";
|
||||
case SDL_EVENT_WINDOW_OCCLUDED: return "window_occluded";
|
||||
case SDL_EVENT_WINDOW_ENTER_FULLSCREEN: return "window_enter_fullscreen";
|
||||
case SDL_EVENT_WINDOW_LEAVE_FULLSCREEN: return "window_leave_fullscreen";
|
||||
case SDL_EVENT_WINDOW_DESTROYED: return "window_destroyed";
|
||||
case SDL_EVENT_WINDOW_HDR_STATE_CHANGED: return "window_hdr_state_changed";
|
||||
|
||||
// Keyboard events
|
||||
case SDL_EVENT_KEY_DOWN: return "key_down";
|
||||
case SDL_EVENT_KEY_UP: return "key_up";
|
||||
case SDL_EVENT_TEXT_EDITING: return "text_editing";
|
||||
case SDL_EVENT_TEXT_INPUT: return "text_input";
|
||||
case SDL_EVENT_KEYMAP_CHANGED: return "keymap_changed";
|
||||
case SDL_EVENT_KEYBOARD_ADDED: return "keyboard_added";
|
||||
case SDL_EVENT_KEYBOARD_REMOVED: return "keyboard_removed";
|
||||
case SDL_EVENT_TEXT_EDITING_CANDIDATES: return "text_editing_candidates";
|
||||
|
||||
// Mouse events
|
||||
case SDL_EVENT_MOUSE_MOTION: return "mouse_motion";
|
||||
case SDL_EVENT_MOUSE_BUTTON_DOWN: return "mouse_button_down";
|
||||
case SDL_EVENT_MOUSE_BUTTON_UP: return "mouse_button_up";
|
||||
case SDL_EVENT_MOUSE_WHEEL: return "mouse_wheel";
|
||||
case SDL_EVENT_MOUSE_ADDED: return "mouse_added";
|
||||
case SDL_EVENT_MOUSE_REMOVED: return "mouse_removed";
|
||||
|
||||
// Joystick events
|
||||
case SDL_EVENT_JOYSTICK_AXIS_MOTION: return "joystick_axis_motion";
|
||||
case SDL_EVENT_JOYSTICK_BALL_MOTION: return "joystick_ball_motion";
|
||||
case SDL_EVENT_JOYSTICK_HAT_MOTION: return "joystick_hat_motion";
|
||||
case SDL_EVENT_JOYSTICK_BUTTON_DOWN: return "joystick_button_down";
|
||||
case SDL_EVENT_JOYSTICK_BUTTON_UP: return "joystick_button_up";
|
||||
case SDL_EVENT_JOYSTICK_ADDED: return "joystick_added";
|
||||
case SDL_EVENT_JOYSTICK_REMOVED: return "joystick_removed";
|
||||
case SDL_EVENT_JOYSTICK_BATTERY_UPDATED: return "joystick_battery_updated";
|
||||
case SDL_EVENT_JOYSTICK_UPDATE_COMPLETE: return "joystick_update_complete";
|
||||
|
||||
// Gamepad events
|
||||
case SDL_EVENT_GAMEPAD_AXIS_MOTION: return "gamepad_axis_motion";
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_DOWN: return "gamepad_button_down";
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_UP: return "gamepad_button_up";
|
||||
case SDL_EVENT_GAMEPAD_ADDED: return "gamepad_added";
|
||||
case SDL_EVENT_GAMEPAD_REMOVED: return "gamepad_removed";
|
||||
case SDL_EVENT_GAMEPAD_REMAPPED: return "gamepad_remapped";
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN: return "gamepad_touchpad_down";
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION: return "gamepad_touchpad_motion";
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_UP: return "gamepad_touchpad_up";
|
||||
case SDL_EVENT_GAMEPAD_SENSOR_UPDATE: return "gamepad_sensor_update";
|
||||
case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE: return "gamepad_update_complete";
|
||||
case SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED: return "gamepad_steam_handle_updated";
|
||||
|
||||
// Touch events
|
||||
case SDL_EVENT_FINGER_DOWN: return "finger_down";
|
||||
case SDL_EVENT_FINGER_UP: return "finger_up";
|
||||
case SDL_EVENT_FINGER_MOTION: return "finger_motion";
|
||||
|
||||
// Clipboard events
|
||||
case SDL_EVENT_CLIPBOARD_UPDATE: return "clipboard_update";
|
||||
|
||||
// Drag and drop events
|
||||
case SDL_EVENT_DROP_FILE: return "drop_file";
|
||||
case SDL_EVENT_DROP_TEXT: return "drop_text";
|
||||
case SDL_EVENT_DROP_BEGIN: return "drop_begin";
|
||||
case SDL_EVENT_DROP_COMPLETE: return "drop_complete";
|
||||
case SDL_EVENT_DROP_POSITION: return "drop_position";
|
||||
|
||||
// Audio device events
|
||||
case SDL_EVENT_AUDIO_DEVICE_ADDED: return "audio_device_added";
|
||||
case SDL_EVENT_AUDIO_DEVICE_REMOVED: return "audio_device_removed";
|
||||
case SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED: return "audio_device_format_changed";
|
||||
|
||||
// Sensor events
|
||||
case SDL_EVENT_SENSOR_UPDATE: return "sensor_update";
|
||||
|
||||
// Pen events
|
||||
case SDL_EVENT_PEN_PROXIMITY_IN: return "pen_proximity_in";
|
||||
case SDL_EVENT_PEN_PROXIMITY_OUT: return "pen_proximity_out";
|
||||
case SDL_EVENT_PEN_DOWN: return "pen_down";
|
||||
case SDL_EVENT_PEN_UP: return "pen_up";
|
||||
case SDL_EVENT_PEN_BUTTON_DOWN: return "pen_button_down";
|
||||
case SDL_EVENT_PEN_BUTTON_UP: return "pen_button_up";
|
||||
case SDL_EVENT_PEN_MOTION: return "pen_motion";
|
||||
case SDL_EVENT_PEN_AXIS: return "pen_axis";
|
||||
|
||||
// Camera events
|
||||
case SDL_EVENT_CAMERA_DEVICE_ADDED: return "camera_device_added";
|
||||
case SDL_EVENT_CAMERA_DEVICE_REMOVED: return "camera_device_removed";
|
||||
case SDL_EVENT_CAMERA_DEVICE_APPROVED: return "camera_device_approved";
|
||||
case SDL_EVENT_CAMERA_DEVICE_DENIED: return "camera_device_denied";
|
||||
|
||||
// Render events
|
||||
case SDL_EVENT_RENDER_TARGETS_RESET: return "render_targets_reset";
|
||||
case SDL_EVENT_RENDER_DEVICE_RESET: return "render_device_reset";
|
||||
case SDL_EVENT_RENDER_DEVICE_LOST: return "render_device_lost";
|
||||
|
||||
// User event (assuming it should be included)
|
||||
case SDL_EVENT_USER: return "user";
|
||||
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
const char* mouse_button_to_string(int mouse) {
|
||||
switch (mouse) {
|
||||
case SDL_BUTTON_LEFT: return "left";
|
||||
case SDL_BUTTON_MIDDLE: return "middle";
|
||||
case SDL_BUTTON_RIGHT: return "right";
|
||||
case SDL_BUTTON_X1: return "x1";
|
||||
case SDL_BUTTON_X2: return "x2";
|
||||
default: return "left";
|
||||
}
|
||||
}
|
||||
|
||||
static void wota_write_vec2(WotaBuffer *wb, double x, double y) {
|
||||
// We'll store as WOTA_ARR of length 2, then two numbers
|
||||
wota_write_array(wb, 2);
|
||||
wota_write_number(wb, x);
|
||||
wota_write_number(wb, y);
|
||||
}
|
||||
|
||||
static int event2wota_count_props(const SDL_Event *event)
|
||||
{
|
||||
// We always store at least "type" and "timestamp".
|
||||
int count = 2;
|
||||
|
||||
switch (event->type) {
|
||||
|
||||
case SDL_EVENT_AUDIO_DEVICE_ADDED:
|
||||
case SDL_EVENT_AUDIO_DEVICE_REMOVED:
|
||||
count += 2; // which, recording
|
||||
break;
|
||||
|
||||
case SDL_EVENT_DISPLAY_ORIENTATION:
|
||||
case SDL_EVENT_DISPLAY_ADDED:
|
||||
case SDL_EVENT_DISPLAY_REMOVED:
|
||||
case SDL_EVENT_DISPLAY_MOVED:
|
||||
case SDL_EVENT_DISPLAY_DESKTOP_MODE_CHANGED:
|
||||
case SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED:
|
||||
case SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED:
|
||||
count += 3; // which, orientation/data1, data2
|
||||
break;
|
||||
|
||||
case SDL_EVENT_MOUSE_MOTION:
|
||||
count += 5;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_MOUSE_WHEEL:
|
||||
// window, which, scroll, mouse => 4 extra
|
||||
count += 4;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_MOUSE_BUTTON_UP:
|
||||
case SDL_EVENT_MOUSE_BUTTON_DOWN:
|
||||
// window, which, down, button, clicks, mouse => 6 extra
|
||||
count += 6;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_SENSOR_UPDATE:
|
||||
// which, sensor_timestamp => 2 extra
|
||||
count += 2;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_KEY_DOWN:
|
||||
case SDL_EVENT_KEY_UP:
|
||||
// window, which, down, repeat, key, scancode, mod => 7 extra
|
||||
count += 7;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_FINGER_MOTION:
|
||||
case SDL_EVENT_FINGER_DOWN:
|
||||
case SDL_EVENT_FINGER_UP:
|
||||
// touch, finger, pos, d_pos, pressure, window => 6 extra
|
||||
count += 6;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_DROP_BEGIN:
|
||||
case SDL_EVENT_DROP_FILE:
|
||||
case SDL_EVENT_DROP_TEXT:
|
||||
case SDL_EVENT_DROP_COMPLETE:
|
||||
case SDL_EVENT_DROP_POSITION:
|
||||
// window, pos, data, source => 4 extra
|
||||
count += 4;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_TEXT_INPUT:
|
||||
// window, text, mod => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_CAMERA_DEVICE_APPROVED:
|
||||
case SDL_EVENT_CAMERA_DEVICE_REMOVED:
|
||||
case SDL_EVENT_CAMERA_DEVICE_ADDED:
|
||||
case SDL_EVENT_CAMERA_DEVICE_DENIED:
|
||||
// which => 1 extra
|
||||
count += 1;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_CLIPBOARD_UPDATE:
|
||||
// owner => 1 extra
|
||||
count += 1;
|
||||
break;
|
||||
|
||||
/* Window events that only need 'which' */
|
||||
case SDL_EVENT_WINDOW_EXPOSED:
|
||||
case SDL_EVENT_WINDOW_FOCUS_GAINED:
|
||||
case SDL_EVENT_WINDOW_FOCUS_LOST:
|
||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
|
||||
// which => 1 extra
|
||||
count += 1;
|
||||
break;
|
||||
|
||||
/* Window events that need data1 and data2 */
|
||||
case SDL_EVENT_WINDOW_SHOWN:
|
||||
case SDL_EVENT_WINDOW_HIDDEN:
|
||||
case SDL_EVENT_WINDOW_MOVED:
|
||||
case SDL_EVENT_WINDOW_RESIZED:
|
||||
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
|
||||
case SDL_EVENT_WINDOW_METAL_VIEW_RESIZED:
|
||||
case SDL_EVENT_WINDOW_MINIMIZED:
|
||||
case SDL_EVENT_WINDOW_MAXIMIZED:
|
||||
case SDL_EVENT_WINDOW_RESTORED:
|
||||
case SDL_EVENT_WINDOW_MOUSE_ENTER:
|
||||
case SDL_EVENT_WINDOW_MOUSE_LEAVE:
|
||||
case SDL_EVENT_WINDOW_HIT_TEST:
|
||||
case SDL_EVENT_WINDOW_ICCPROF_CHANGED:
|
||||
case SDL_EVENT_WINDOW_DISPLAY_CHANGED:
|
||||
case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
|
||||
case SDL_EVENT_WINDOW_OCCLUDED:
|
||||
case SDL_EVENT_WINDOW_ENTER_FULLSCREEN:
|
||||
case SDL_EVENT_WINDOW_LEAVE_FULLSCREEN:
|
||||
case SDL_EVENT_WINDOW_DESTROYED:
|
||||
case SDL_EVENT_WINDOW_HDR_STATE_CHANGED:
|
||||
// which, x/width/display_index, y/height => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_WINDOW_SAFE_AREA_CHANGED:
|
||||
// which, x, y, width, height => 5 extra
|
||||
count += 5;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_JOYSTICK_ADDED:
|
||||
case SDL_EVENT_JOYSTICK_REMOVED:
|
||||
case SDL_EVENT_JOYSTICK_UPDATE_COMPLETE:
|
||||
// which => 1 extra
|
||||
count += 1;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_JOYSTICK_AXIS_MOTION:
|
||||
// which, axis, value => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_JOYSTICK_BALL_MOTION:
|
||||
// which, ball, rel => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_JOYSTICK_BUTTON_DOWN:
|
||||
case SDL_EVENT_JOYSTICK_BUTTON_UP:
|
||||
// which, button, down => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_GAMEPAD_ADDED:
|
||||
case SDL_EVENT_GAMEPAD_REMOVED:
|
||||
case SDL_EVENT_GAMEPAD_REMAPPED:
|
||||
case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE:
|
||||
case SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED:
|
||||
// which => 1 extra
|
||||
count += 1;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_GAMEPAD_AXIS_MOTION:
|
||||
// which, axis, value => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_UP:
|
||||
// which, button, down => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN:
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION:
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_UP:
|
||||
// which, touchpad, finger, pos, pressure => 5 extra
|
||||
count += 5;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_GAMEPAD_SENSOR_UPDATE:
|
||||
// which, sensor, sensor_timestamp => 3 extra
|
||||
count += 3;
|
||||
break;
|
||||
|
||||
case SDL_EVENT_USER:
|
||||
// cb => 1 extra
|
||||
count += 1;
|
||||
break;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
static void event2wota_write(WotaBuffer *wb, const SDL_Event *e, int c) {
|
||||
wota_write_record(wb, (unsigned long long)c);
|
||||
wota_write_text(wb, "type");
|
||||
wota_write_text(wb, event_type_to_string(e->type));
|
||||
wota_write_text(wb, "timestamp");
|
||||
wota_write_number(wb, (double)e->common.timestamp);
|
||||
switch(e->type) {
|
||||
case SDL_EVENT_AUDIO_DEVICE_ADDED:
|
||||
case SDL_EVENT_AUDIO_DEVICE_REMOVED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->adevice.which);
|
||||
wota_write_text(wb, "recording");
|
||||
wota_write_sym(wb, e->adevice.recording ? WOTA_TRUE : WOTA_FALSE);
|
||||
break;
|
||||
case SDL_EVENT_DISPLAY_ORIENTATION:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->display.displayID);
|
||||
wota_write_text(wb, "orientation");
|
||||
wota_write_number(wb, (double)e->display.data1);
|
||||
wota_write_text(wb, "data2");
|
||||
wota_write_number(wb, (double)e->display.data2);
|
||||
break;
|
||||
case SDL_EVENT_DISPLAY_ADDED:
|
||||
case SDL_EVENT_DISPLAY_REMOVED:
|
||||
case SDL_EVENT_DISPLAY_MOVED:
|
||||
case SDL_EVENT_DISPLAY_DESKTOP_MODE_CHANGED:
|
||||
case SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED:
|
||||
case SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->display.displayID);
|
||||
wota_write_text(wb, "data1");
|
||||
wota_write_number(wb, (double)e->display.data1);
|
||||
wota_write_text(wb, "data2");
|
||||
wota_write_number(wb, (double)e->display.data2);
|
||||
break;
|
||||
case SDL_EVENT_MOUSE_MOTION:
|
||||
wota_write_text(wb, "window");
|
||||
wota_write_number(wb, (double)e->motion.windowID);
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->motion.which);
|
||||
wota_write_text(wb, "state");
|
||||
wota_write_number(wb, (double)e->motion.state);
|
||||
wota_write_text(wb, "pos");
|
||||
wota_write_vec2(wb, (double)e->motion.x, (double)e->motion.y);
|
||||
wota_write_text(wb, "d_pos");
|
||||
wota_write_vec2(wb, (double)e->motion.xrel, (double)e->motion.yrel);
|
||||
break;
|
||||
case SDL_EVENT_MOUSE_WHEEL:
|
||||
wota_write_text(wb, "window");
|
||||
wota_write_number(wb, (double)e->wheel.windowID);
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->wheel.which);
|
||||
wota_write_text(wb, "scroll");
|
||||
wota_write_vec2(wb, (double)e->wheel.x, (double)e->wheel.y);
|
||||
wota_write_text(wb, "pos");
|
||||
wota_write_vec2(wb, (double)e->wheel.mouse_x, (double)e->wheel.mouse_y);
|
||||
break;
|
||||
case SDL_EVENT_MOUSE_BUTTON_UP:
|
||||
case SDL_EVENT_MOUSE_BUTTON_DOWN:
|
||||
wota_write_text(wb, "window");
|
||||
wota_write_number(wb, (double)e->button.windowID);
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->button.which);
|
||||
wota_write_text(wb, "down");
|
||||
wota_write_sym(wb, e->button.down ? WOTA_TRUE : WOTA_FALSE);
|
||||
wota_write_text(wb, "button");
|
||||
wota_write_text(wb, mouse_button_to_string(e->button.button));
|
||||
wota_write_text(wb, "clicks");
|
||||
wota_write_number(wb, (double)e->button.clicks);
|
||||
wota_write_text(wb, "pos");
|
||||
wota_write_vec2(wb, (double)e->button.x, (double)e->button.y);
|
||||
break;
|
||||
case SDL_EVENT_SENSOR_UPDATE:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->sensor.which);
|
||||
wota_write_text(wb, "sensor_timestamp");
|
||||
wota_write_number(wb, (double)e->sensor.sensor_timestamp);
|
||||
break;
|
||||
case SDL_EVENT_KEY_DOWN:
|
||||
case SDL_EVENT_KEY_UP:
|
||||
wota_write_text(wb, "window");
|
||||
wota_write_number(wb, (double)e->key.windowID);
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->key.which);
|
||||
wota_write_text(wb, "down");
|
||||
wota_write_sym(wb, e->key.down ? WOTA_TRUE : WOTA_FALSE);
|
||||
wota_write_text(wb, "repeat");
|
||||
wota_write_sym(wb, e->key.repeat ? WOTA_TRUE : WOTA_FALSE);
|
||||
wota_write_text(wb, "key");
|
||||
wota_write_number(wb, (double)e->key.key);
|
||||
wota_write_text(wb, "scancode");
|
||||
wota_write_number(wb, (double)e->key.scancode);
|
||||
wota_write_text(wb, "mod");
|
||||
wota_write_number(wb, (double)e->key.mod);
|
||||
break;
|
||||
case SDL_EVENT_FINGER_MOTION:
|
||||
case SDL_EVENT_FINGER_DOWN:
|
||||
case SDL_EVENT_FINGER_UP:
|
||||
wota_write_text(wb, "touch");
|
||||
wota_write_number(wb, (double)e->tfinger.touchID);
|
||||
wota_write_text(wb, "finger");
|
||||
wota_write_number(wb, (double)e->tfinger.fingerID);
|
||||
wota_write_text(wb, "pos");
|
||||
wota_write_vec2(wb, (double)e->tfinger.x, (double)e->tfinger.y);
|
||||
wota_write_text(wb, "d_pos");
|
||||
wota_write_vec2(wb, (double)e->tfinger.dx, (double)e->tfinger.dy);
|
||||
wota_write_text(wb, "pressure");
|
||||
wota_write_number(wb, (double)e->tfinger.pressure);
|
||||
wota_write_text(wb, "window");
|
||||
wota_write_number(wb, (double)e->key.windowID);
|
||||
break;
|
||||
case SDL_EVENT_DROP_BEGIN:
|
||||
case SDL_EVENT_DROP_FILE:
|
||||
case SDL_EVENT_DROP_TEXT:
|
||||
case SDL_EVENT_DROP_COMPLETE:
|
||||
case SDL_EVENT_DROP_POSITION:
|
||||
wota_write_text(wb, "window");
|
||||
wota_write_number(wb, (double)e->drop.windowID);
|
||||
wota_write_text(wb, "pos");
|
||||
wota_write_vec2(wb, (double)e->drop.x, (double)e->drop.y);
|
||||
wota_write_text(wb, "data");
|
||||
wota_write_text(wb, e->drop.data ? e->drop.data : "");
|
||||
wota_write_text(wb, "source");
|
||||
wota_write_text(wb, e->drop.source ? e->drop.source : "");
|
||||
break;
|
||||
case SDL_EVENT_TEXT_INPUT:
|
||||
wota_write_text(wb, "window");
|
||||
wota_write_number(wb, (double)e->text.windowID);
|
||||
wota_write_text(wb, "text");
|
||||
wota_write_text(wb, e->text.text);
|
||||
wota_write_text(wb, "mod");
|
||||
wota_write_number(wb, 0);
|
||||
break;
|
||||
case SDL_EVENT_CAMERA_DEVICE_APPROVED:
|
||||
case SDL_EVENT_CAMERA_DEVICE_REMOVED:
|
||||
case SDL_EVENT_CAMERA_DEVICE_ADDED:
|
||||
case SDL_EVENT_CAMERA_DEVICE_DENIED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->cdevice.which);
|
||||
break;
|
||||
case SDL_EVENT_CLIPBOARD_UPDATE:
|
||||
wota_write_text(wb, "owner");
|
||||
wota_write_sym(wb, e->clipboard.owner ? WOTA_TRUE : WOTA_FALSE);
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_EXPOSED:
|
||||
case SDL_EVENT_WINDOW_FOCUS_GAINED:
|
||||
case SDL_EVENT_WINDOW_FOCUS_LOST:
|
||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->window.windowID);
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_SHOWN:
|
||||
case SDL_EVENT_WINDOW_HIDDEN:
|
||||
case SDL_EVENT_WINDOW_MINIMIZED:
|
||||
case SDL_EVENT_WINDOW_MAXIMIZED:
|
||||
case SDL_EVENT_WINDOW_RESTORED:
|
||||
case SDL_EVENT_WINDOW_MOUSE_ENTER:
|
||||
case SDL_EVENT_WINDOW_MOUSE_LEAVE:
|
||||
case SDL_EVENT_WINDOW_HIT_TEST:
|
||||
case SDL_EVENT_WINDOW_ICCPROF_CHANGED:
|
||||
case SDL_EVENT_WINDOW_OCCLUDED:
|
||||
case SDL_EVENT_WINDOW_ENTER_FULLSCREEN:
|
||||
case SDL_EVENT_WINDOW_LEAVE_FULLSCREEN:
|
||||
case SDL_EVENT_WINDOW_DESTROYED:
|
||||
case SDL_EVENT_WINDOW_HDR_STATE_CHANGED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->window.windowID);
|
||||
wota_write_text(wb, "data1");
|
||||
wota_write_number(wb, (double)e->window.data1);
|
||||
wota_write_text(wb, "data2");
|
||||
wota_write_number(wb, (double)e->window.data2);
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_SAFE_AREA_CHANGED:
|
||||
{
|
||||
SDL_Window *window = SDL_GetWindowFromID(e->window.windowID);
|
||||
SDL_Rect safe_area = {0, 0, 0, 0};
|
||||
if (window && SDL_GetWindowSafeArea(window, &safe_area)) {
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->window.windowID);
|
||||
wota_write_text(wb, "x");
|
||||
wota_write_number(wb, (double)safe_area.x);
|
||||
wota_write_text(wb, "y");
|
||||
wota_write_number(wb, (double)safe_area.y);
|
||||
wota_write_text(wb, "width");
|
||||
wota_write_number(wb, (double)safe_area.w);
|
||||
wota_write_text(wb, "height");
|
||||
wota_write_number(wb, (double)safe_area.h);
|
||||
} else {
|
||||
// Fallback to original behavior if SDL_GetWindowSafeArea fails
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->window.windowID);
|
||||
wota_write_text(wb, "data1");
|
||||
wota_write_number(wb, (double)e->window.data1);
|
||||
wota_write_text(wb, "data2");
|
||||
wota_write_number(wb, (double)e->window.data2);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_MOVED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->window.windowID);
|
||||
wota_write_text(wb, "x");
|
||||
wota_write_number(wb, (double)e->window.data1);
|
||||
wota_write_text(wb, "y");
|
||||
wota_write_number(wb, (double)e->window.data2);
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_RESIZED:
|
||||
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
|
||||
case SDL_EVENT_WINDOW_METAL_VIEW_RESIZED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->window.windowID);
|
||||
wota_write_text(wb, "width");
|
||||
wota_write_number(wb, (double)e->window.data1);
|
||||
wota_write_text(wb, "height");
|
||||
wota_write_number(wb, (double)e->window.data2);
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_DISPLAY_CHANGED:
|
||||
case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->window.windowID);
|
||||
wota_write_text(wb, "display_index");
|
||||
wota_write_number(wb, (double)e->window.data1);
|
||||
wota_write_text(wb, "data2");
|
||||
wota_write_number(wb, (double)e->window.data2);
|
||||
break;
|
||||
case SDL_EVENT_JOYSTICK_ADDED:
|
||||
case SDL_EVENT_JOYSTICK_REMOVED:
|
||||
case SDL_EVENT_JOYSTICK_UPDATE_COMPLETE:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->jdevice.which);
|
||||
break;
|
||||
case SDL_EVENT_JOYSTICK_AXIS_MOTION:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->jaxis.which);
|
||||
wota_write_text(wb, "axis");
|
||||
wota_write_number(wb, (double)e->jaxis.axis);
|
||||
wota_write_text(wb, "value");
|
||||
wota_write_number(wb, (double)e->jaxis.value);
|
||||
break;
|
||||
case SDL_EVENT_JOYSTICK_BALL_MOTION:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->jball.which);
|
||||
wota_write_text(wb, "ball");
|
||||
wota_write_number(wb, (double)e->jball.ball);
|
||||
wota_write_text(wb, "rel");
|
||||
wota_write_vec2(wb, (double)e->jball.xrel, (double)e->jball.yrel);
|
||||
break;
|
||||
case SDL_EVENT_JOYSTICK_BUTTON_DOWN:
|
||||
case SDL_EVENT_JOYSTICK_BUTTON_UP:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->jbutton.which);
|
||||
wota_write_text(wb, "button");
|
||||
wota_write_number(wb, (double)e->jbutton.button);
|
||||
wota_write_text(wb, "down");
|
||||
wota_write_sym(wb, e->jbutton.down ? WOTA_TRUE : WOTA_FALSE);
|
||||
break;
|
||||
case SDL_EVENT_GAMEPAD_ADDED:
|
||||
case SDL_EVENT_GAMEPAD_REMOVED:
|
||||
case SDL_EVENT_GAMEPAD_REMAPPED:
|
||||
case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE:
|
||||
case SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->gdevice.which);
|
||||
break;
|
||||
case SDL_EVENT_GAMEPAD_AXIS_MOTION:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->gaxis.which);
|
||||
wota_write_text(wb, "axis");
|
||||
wota_write_text(wb, SDL_GetGamepadStringForAxis(e->gaxis.axis));
|
||||
wota_write_text(wb, "value");
|
||||
// Normalize axis values
|
||||
double normalized_value;
|
||||
if (e->gaxis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER ||
|
||||
e->gaxis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) {
|
||||
// Triggers: 0 to 32767 -> 0 to 1
|
||||
normalized_value = (double)e->gaxis.value / 32767.0;
|
||||
} else {
|
||||
// Thumbsticks: -32768 to 32767 -> -1 to 1
|
||||
normalized_value = (double)e->gaxis.value / 32767.0;
|
||||
}
|
||||
wota_write_number(wb, normalized_value);
|
||||
break;
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_UP:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->gbutton.which);
|
||||
wota_write_text(wb, "button");
|
||||
wota_write_text(wb, SDL_GetGamepadStringForButton(e->gbutton.button));
|
||||
wota_write_text(wb, "down");
|
||||
wota_write_sym(wb, e->gbutton.down ? WOTA_TRUE : WOTA_FALSE);
|
||||
break;
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN:
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION:
|
||||
case SDL_EVENT_GAMEPAD_TOUCHPAD_UP:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->gtouchpad.which);
|
||||
wota_write_text(wb, "touchpad");
|
||||
wota_write_number(wb, (double)e->gtouchpad.touchpad);
|
||||
wota_write_text(wb, "finger");
|
||||
wota_write_number(wb, (double)e->gtouchpad.finger);
|
||||
wota_write_text(wb, "pos");
|
||||
wota_write_vec2(wb, (double)e->gtouchpad.x, (double)e->gtouchpad.y);
|
||||
wota_write_text(wb, "pressure");
|
||||
wota_write_number(wb, (double)e->gtouchpad.pressure);
|
||||
break;
|
||||
case SDL_EVENT_GAMEPAD_SENSOR_UPDATE:
|
||||
wota_write_text(wb, "which");
|
||||
wota_write_number(wb, (double)e->gsensor.which);
|
||||
wota_write_text(wb, "sensor");
|
||||
wota_write_number(wb, (double)e->gsensor.sensor);
|
||||
wota_write_text(wb, "sensor_timestamp");
|
||||
wota_write_number(wb, (double)e->gsensor.sensor_timestamp);
|
||||
break;
|
||||
case SDL_EVENT_USER:
|
||||
wota_write_text(wb, "cb");
|
||||
wota_write_number(wb, (double)(uintptr_t)e->user.data1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static WotaBuffer event2wota(const SDL_Event *event) {
|
||||
WotaBuffer wb;
|
||||
wota_buffer_init(&wb, 8);
|
||||
int n = event2wota_count_props(event);
|
||||
event2wota_write(&wb, event, n);
|
||||
return wb;
|
||||
}
|
||||
|
||||
// Get all events directly from SDL event queue
|
||||
JSC_CCALL(input_get_events,
|
||||
JSValue events_array = JS_NewArray(js);
|
||||
SDL_Event event;
|
||||
int event_count = 0;
|
||||
|
||||
while (SDL_PollEvent(&event)) {
|
||||
gui_input(&event);
|
||||
|
||||
WotaBuffer wb = event2wota(&event);
|
||||
JSValue event_obj = wota2value(js, wb.data);
|
||||
JS_SetPropertyUint32(js, events_array, event_count, event_obj);
|
||||
wota_buffer_free(&wb);
|
||||
event_count++;
|
||||
}
|
||||
|
||||
return events_array;
|
||||
)
|
||||
|
||||
JSC_CCALL(input_gamepad_id_to_type,
|
||||
int id = js2number(js, argv[0]);
|
||||
return JS_NewString(js, SDL_GetGamepadStringForType(SDL_GetGamepadTypeForID(id)));
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_input_funcs[] = {
|
||||
MIST_FUNC_DEF(input, mouse_show, 1),
|
||||
MIST_FUNC_DEF(input, mouse_lock, 1),
|
||||
MIST_FUNC_DEF(input, keyname, 1),
|
||||
MIST_FUNC_DEF(input, keymod, 0),
|
||||
MIST_FUNC_DEF(input, mousestate, 0),
|
||||
MIST_FUNC_DEF(input, get_events, 0),
|
||||
MIST_FUNC_DEF(input, gamepad_id_to_type, 1),
|
||||
};
|
||||
|
||||
JSValue js_input_use(JSContext *js) {
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js,mod,js_input_funcs,countof(js_input_funcs));
|
||||
return mod;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
#ifndef QJS_SDL_INPUT_H
|
||||
#define QJS_SDL_INPUT_H
|
||||
|
||||
#include <quickjs.h>
|
||||
|
||||
const char* event_type_to_string(uint32_t event_type);
|
||||
const char* mouse_button_to_string(int mouse);
|
||||
|
||||
// JavaScript module entry point
|
||||
JSValue js_input_use(JSContext *js);
|
||||
|
||||
#endif // QJS_SDL_INPUT_H
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,19 +0,0 @@
|
||||
#ifndef QJS_SDL_SURFACE_H
|
||||
#define QJS_SDL_SURFACE_H
|
||||
|
||||
#include "cell.h"
|
||||
#include <SDL3/SDL_surface.h>
|
||||
|
||||
JSValue js_sdl_surface_use(JSContext *js);
|
||||
|
||||
// Functions generated by QJSCLASS macro
|
||||
JSValue SDL_Surface2js(JSContext *js, SDL_Surface *s);
|
||||
SDL_Surface *js2SDL_Surface(JSContext *js, JSValue val);
|
||||
|
||||
// Free function for SDL_Surface
|
||||
void SDL_Surface_free(JSRuntime *rt, SDL_Surface *s);
|
||||
|
||||
// Class ID for SDL_Surface
|
||||
extern JSClassID js_SDL_Surface_id;
|
||||
|
||||
#endif
|
||||
@@ -1,798 +0,0 @@
|
||||
#include "cell.h"
|
||||
#include "jsffi.h"
|
||||
#include "qjs_sdl_surface.h"
|
||||
#include "qjs_actor.h"
|
||||
#include "sprite.h"
|
||||
#include "transform.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3/SDL_gpu.h>
|
||||
#include <SDL3/SDL_error.h>
|
||||
#include <SDL3/SDL_properties.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
#include "qjs_sdl.h"
|
||||
|
||||
// SDL Window free function
|
||||
void SDL_Window_free(JSRuntime *rt, SDL_Window *w)
|
||||
{
|
||||
SDL_DestroyWindow(w);
|
||||
}
|
||||
|
||||
QJSCLASS(SDL_Window,)
|
||||
|
||||
void SDL_Cursor_free(JSRuntime *rt, SDL_Cursor *c)
|
||||
{
|
||||
SDL_DestroyCursor(c);
|
||||
}
|
||||
|
||||
QJSCLASS(SDL_Cursor,)
|
||||
|
||||
// External function declarations
|
||||
extern JSValue rect2js(JSContext *js, rect r);
|
||||
extern rect js2rect(JSContext *js, JSValue v);
|
||||
extern HMM_Vec2 js2vec2(JSContext *js, JSValue v);
|
||||
extern JSValue vec22js(JSContext *js, HMM_Vec2 v);
|
||||
extern colorf js2color(JSContext *js, JSValue v);
|
||||
extern double js2number(JSContext *js, JSValue v);
|
||||
extern JSValue number2js(JSContext *js, double n);
|
||||
extern SDL_Window *js2SDL_Window(JSContext *js, JSValue v);
|
||||
extern JSValue SDL_Window2js(JSContext *js, SDL_Window *w);
|
||||
extern void *get_gpu_buffer(JSContext *js, JSValue argv, size_t *stride, size_t *size);
|
||||
extern double js_getnum_str(JSContext *js, JSValue v, const char *str);
|
||||
extern sprite *js2sprite(JSContext *js, JSValue v);
|
||||
extern HMM_Vec3 js2vec3(JSContext *js, JSValue v);
|
||||
extern JSValue vec32js(JSContext *js, HMM_Vec3 v);
|
||||
extern HMM_Vec4 js2vec4(JSContext *js, JSValue v);
|
||||
extern JSValue vec42js(JSContext *js, HMM_Vec4 v);
|
||||
extern JSValue make_gpu_buffer(JSContext *js, void *data, size_t size, int type, int elements, int copy, int index);
|
||||
extern JSValue make_quad_indices_buffer(JSContext *js, int quads);
|
||||
extern JSClassID js_SDL_Surface_id;
|
||||
|
||||
// Forward declarations for blend mode helpers
|
||||
static JSValue blendmode2js(JSContext *js, SDL_BlendMode mode);
|
||||
static SDL_BlendMode js2blendmode(JSContext *js, JSValue v);
|
||||
|
||||
// Window constructor function
|
||||
static JSValue js_window_constructor(JSContext *js, JSValueConst new_target, int argc, JSValueConst *argv)
|
||||
{
|
||||
SDL_Window *www = SDL_CreateWindow("prosperon", 500, 500, 0);
|
||||
return SDL_Window2js(js, www);
|
||||
if (argc < 1 || !JS_IsObject(argv[0]))
|
||||
return JS_ThrowTypeError(js, "Window constructor requires an object argument");
|
||||
|
||||
JSValue opts = argv[0];
|
||||
|
||||
// Get basic properties (defaults are handled in JavaScript)
|
||||
const char *title = NULL;
|
||||
JSValue title_val = JS_GetPropertyStr(js, opts, "title");
|
||||
if (!JS_IsNull(title_val) && !JS_IsNull(title_val)) {
|
||||
title = JS_ToCString(js, title_val);
|
||||
}
|
||||
JS_FreeValue(js, title_val);
|
||||
|
||||
if (!title) {
|
||||
return JS_ThrowTypeError(js, "Window title is required");
|
||||
}
|
||||
|
||||
int width = 640;
|
||||
JSValue width_val = JS_GetPropertyStr(js, opts, "width");
|
||||
if (!JS_IsNull(width_val) && !JS_IsNull(width_val)) {
|
||||
width = js2number(js, width_val);
|
||||
}
|
||||
JS_FreeValue(js, width_val);
|
||||
|
||||
int height = 480;
|
||||
JSValue height_val = JS_GetPropertyStr(js, opts, "height");
|
||||
if (!JS_IsNull(height_val) && !JS_IsNull(height_val)) {
|
||||
height = js2number(js, height_val);
|
||||
}
|
||||
JS_FreeValue(js, height_val);
|
||||
|
||||
// Create SDL properties object
|
||||
SDL_PropertiesID props = SDL_CreateProperties();
|
||||
|
||||
// Always set basic properties
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, width);
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, height);
|
||||
SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, title);
|
||||
|
||||
// Handle window position
|
||||
JSValue x_val = JS_GetPropertyStr(js, opts, "x");
|
||||
if (!JS_IsNull(x_val)) {
|
||||
if (JS_IsString(x_val)) {
|
||||
const char *pos = JS_ToCString(js, x_val);
|
||||
if (strcmp(pos, "centered") == 0)
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
|
||||
else
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_UNDEFINED);
|
||||
JS_FreeCString(js, pos);
|
||||
} else {
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, js2number(js, x_val));
|
||||
}
|
||||
}
|
||||
JS_FreeValue(js, x_val);
|
||||
|
||||
JSValue y_val = JS_GetPropertyStr(js, opts, "y");
|
||||
if (!JS_IsNull(y_val)) {
|
||||
if (JS_IsString(y_val)) {
|
||||
const char *pos = JS_ToCString(js, y_val);
|
||||
if (strcmp(pos, "centered") == 0)
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
|
||||
else
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_UNDEFINED);
|
||||
JS_FreeCString(js, pos);
|
||||
} else {
|
||||
SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, js2number(js, y_val));
|
||||
}
|
||||
}
|
||||
JS_FreeValue(js, y_val);
|
||||
|
||||
// Helper function to check and set boolean properties
|
||||
#define SET_BOOL_PROP(js_name, sdl_prop) do { \
|
||||
JSValue val = JS_GetPropertyStr(js, opts, js_name); \
|
||||
if (!JS_IsNull(val)) { \
|
||||
SDL_SetBooleanProperty(props, sdl_prop, JS_ToBool(js, val)); \
|
||||
} \
|
||||
JS_FreeValue(js, val); \
|
||||
} while(0)
|
||||
|
||||
// Set all boolean properties directly on the SDL properties object
|
||||
SET_BOOL_PROP("resizable", SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN);
|
||||
SET_BOOL_PROP("fullscreen", SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN);
|
||||
SET_BOOL_PROP("hidden", SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN);
|
||||
SET_BOOL_PROP("borderless", SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN);
|
||||
SET_BOOL_PROP("alwaysOnTop", SDL_PROP_WINDOW_CREATE_ALWAYS_ON_TOP_BOOLEAN);
|
||||
SET_BOOL_PROP("minimized", SDL_PROP_WINDOW_CREATE_MINIMIZED_BOOLEAN);
|
||||
SET_BOOL_PROP("maximized", SDL_PROP_WINDOW_CREATE_MAXIMIZED_BOOLEAN);
|
||||
SET_BOOL_PROP("mouseGrabbed", SDL_PROP_WINDOW_CREATE_MOUSE_GRABBED_BOOLEAN);
|
||||
SET_BOOL_PROP("highPixelDensity", SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN);
|
||||
SET_BOOL_PROP("transparent", SDL_PROP_WINDOW_CREATE_TRANSPARENT_BOOLEAN);
|
||||
SET_BOOL_PROP("utility", SDL_PROP_WINDOW_CREATE_UTILITY_BOOLEAN);
|
||||
SET_BOOL_PROP("tooltip", SDL_PROP_WINDOW_CREATE_TOOLTIP_BOOLEAN);
|
||||
SET_BOOL_PROP("popupMenu", SDL_PROP_WINDOW_CREATE_MENU_BOOLEAN);
|
||||
SET_BOOL_PROP("opengl", SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN);
|
||||
SET_BOOL_PROP("vulkan", SDL_PROP_WINDOW_CREATE_VULKAN_BOOLEAN);
|
||||
SET_BOOL_PROP("metal", SDL_PROP_WINDOW_CREATE_METAL_BOOLEAN);
|
||||
SET_BOOL_PROP("modal", SDL_PROP_WINDOW_CREATE_MODAL_BOOLEAN);
|
||||
SET_BOOL_PROP("externalGraphicsContext", SDL_PROP_WINDOW_CREATE_EXTERNAL_GRAPHICS_CONTEXT_BOOLEAN);
|
||||
|
||||
// Handle focusable (inverse logic)
|
||||
JSValue focusable_val = JS_GetPropertyStr(js, opts, "focusable");
|
||||
if (!JS_IsNull(focusable_val)) {
|
||||
SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN, JS_ToBool(js, focusable_val));
|
||||
}
|
||||
JS_FreeValue(js, focusable_val);
|
||||
|
||||
// Handle notFocusable (for backwards compatibility)
|
||||
JSValue not_focusable_val = JS_GetPropertyStr(js, opts, "notFocusable");
|
||||
if (!JS_IsNull(not_focusable_val)) {
|
||||
SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN, !JS_ToBool(js, not_focusable_val));
|
||||
}
|
||||
JS_FreeValue(js, not_focusable_val);
|
||||
|
||||
#undef SET_BOOL_PROP
|
||||
|
||||
// Handle parent window
|
||||
JSValue parent_val = JS_GetPropertyStr(js, opts, "parent");
|
||||
if (!JS_IsNull(parent_val) && !JS_IsNull(parent_val)) {
|
||||
SDL_Window *parent = js2SDL_Window(js, parent_val);
|
||||
if (parent) {
|
||||
SDL_SetPointerProperty(props, SDL_PROP_WINDOW_CREATE_PARENT_POINTER, parent);
|
||||
}
|
||||
}
|
||||
JS_FreeValue(js, parent_val);
|
||||
|
||||
// Create window with properties
|
||||
SDL_Window *window = SDL_CreateWindowWithProperties(props);
|
||||
SDL_DestroyProperties(props);
|
||||
|
||||
// Always free the title string since we allocated it
|
||||
if (title) {
|
||||
JS_FreeCString(js, title);
|
||||
}
|
||||
|
||||
if (!window) {
|
||||
return JS_ThrowReferenceError(js, "Failed to create window: %s", SDL_GetError());
|
||||
}
|
||||
|
||||
// Create the window JS object
|
||||
JSValue window_obj = SDL_Window2js(js, window);
|
||||
|
||||
// Set additional properties that can't be set during creation
|
||||
// These will be applied through the property setters
|
||||
|
||||
JSValue opacity_val = JS_GetPropertyStr(js, opts, "opacity");
|
||||
if (!JS_IsNull(opacity_val)) {
|
||||
JS_SetPropertyStr(js, window_obj, "opacity", opacity_val);
|
||||
}
|
||||
|
||||
JSValue min_size_val = JS_GetPropertyStr(js, opts, "minimumSize");
|
||||
if (!JS_IsNull(min_size_val)) {
|
||||
JS_SetPropertyStr(js, window_obj, "minimumSize", min_size_val);
|
||||
}
|
||||
|
||||
JSValue max_size_val = JS_GetPropertyStr(js, opts, "maximumSize");
|
||||
if (!JS_IsNull(max_size_val)) {
|
||||
JS_SetPropertyStr(js, window_obj, "maximumSize", max_size_val);
|
||||
}
|
||||
|
||||
JSValue pos_val = JS_GetPropertyStr(js, opts, "position");
|
||||
if (!JS_IsNull(pos_val)) {
|
||||
JS_SetPropertyStr(js, window_obj, "position", pos_val);
|
||||
}
|
||||
|
||||
// Handle text input
|
||||
JSValue text_input = JS_GetPropertyStr(js, opts, "textInput");
|
||||
if (JS_ToBool(js, text_input)) {
|
||||
// SDL_StartTextInput(window);
|
||||
}
|
||||
JS_FreeValue(js, text_input);
|
||||
|
||||
printf("created window %p\n", window);
|
||||
|
||||
return window_obj;
|
||||
}
|
||||
|
||||
JSC_CCALL(SDL_Window_fullscreen,
|
||||
SDL_SetWindowFullscreen(js2SDL_Window(js,self), SDL_WINDOW_FULLSCREEN)
|
||||
)
|
||||
|
||||
JSValue js_SDL_Window_keyboard_shown(JSContext *js, JSValue self) {
|
||||
SDL_Window *window = js2SDL_Window(js,self);
|
||||
return JS_NewBool(js,SDL_ScreenKeyboardShown(window));
|
||||
}
|
||||
|
||||
JSValue js_window_theme(JSContext *js, JSValue self)
|
||||
{
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_safe_area(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_Rect r;
|
||||
SDL_GetWindowSafeArea(w, &r);
|
||||
rect newr;
|
||||
SDL_RectToFRect(&r, &newr);
|
||||
return rect2js(js,newr);
|
||||
}
|
||||
|
||||
JSValue js_window_bordered(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowBordered(w, JS_ToBool(js,argv[0]));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_get_title(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
const char *title = SDL_GetWindowTitle(w);
|
||||
return JS_NewString(js,title);
|
||||
}
|
||||
|
||||
JSValue js_window_set_title(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
const char *title = JS_ToCString(js,val);
|
||||
SDL_SetWindowTitle(w,title);
|
||||
JS_FreeCString(js,title);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_get_size(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *win = js2SDL_Window(js,self);
|
||||
int w, h;
|
||||
SDL_GetWindowSize(win, &w, &h);
|
||||
return vec22js(js, (HMM_Vec2){w,h});
|
||||
}
|
||||
|
||||
JSValue js_window_set_size(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
HMM_Vec2 size = js2vec2(js,val);
|
||||
SDL_SetWindowSize(w,size.x,size.y);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_set_icon(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_Surface *s = js2SDL_Surface(js,argv[0]);
|
||||
if (!SDL_SetWindowIcon(w,s))
|
||||
return JS_ThrowReferenceError(js, "could not set window icon: %s", SDL_GetError());
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Position getter/setter
|
||||
JSValue js_window_get_position(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
int x, y;
|
||||
SDL_GetWindowPosition(w, &x, &y);
|
||||
return vec22js(js, (HMM_Vec2){x,y});
|
||||
}
|
||||
|
||||
JSValue js_window_set_position(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
HMM_Vec2 pos = js2vec2(js,val);
|
||||
SDL_SetWindowPosition(w,pos.x,pos.y);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Mouse grab getter/setter
|
||||
JSValue js_window_get_mouseGrab(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
return JS_NewBool(js, SDL_GetWindowMouseGrab(w));
|
||||
}
|
||||
|
||||
JSValue js_window_set_mouseGrab(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowMouseGrab(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Keyboard grab getter/setter
|
||||
JSValue js_window_get_keyboardGrab(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
return JS_NewBool(js, SDL_GetWindowKeyboardGrab(w));
|
||||
}
|
||||
|
||||
JSValue js_window_set_keyboardGrab(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowKeyboardGrab(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Opacity getter/setter
|
||||
JSValue js_window_get_opacity(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
return number2js(js, SDL_GetWindowOpacity(w));
|
||||
}
|
||||
|
||||
JSValue js_window_set_opacity(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
float opacity = js2number(js,val);
|
||||
SDL_SetWindowOpacity(w, opacity);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Minimum size getter/setter
|
||||
JSValue js_window_get_minimumSize(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
int width, height;
|
||||
SDL_GetWindowMinimumSize(w, &width, &height);
|
||||
return vec22js(js, (HMM_Vec2){width,height});
|
||||
}
|
||||
|
||||
JSValue js_window_set_minimumSize(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
HMM_Vec2 size = js2vec2(js,val);
|
||||
SDL_SetWindowMinimumSize(w,size.x,size.y);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Maximum size getter/setter
|
||||
JSValue js_window_get_maximumSize(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
int width, height;
|
||||
SDL_GetWindowMaximumSize(w, &width, &height);
|
||||
return vec22js(js, (HMM_Vec2){width,height});
|
||||
}
|
||||
|
||||
JSValue js_window_set_maximumSize(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
HMM_Vec2 size = js2vec2(js,val);
|
||||
SDL_SetWindowMaximumSize(w,size.x,size.y);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Resizable setter (read from flags)
|
||||
JSValue js_window_get_resizable(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, flags & SDL_WINDOW_RESIZABLE);
|
||||
}
|
||||
|
||||
JSValue js_window_set_resizable(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowResizable(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Bordered getter/setter
|
||||
JSValue js_window_get_bordered(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, !(flags & SDL_WINDOW_BORDERLESS));
|
||||
}
|
||||
|
||||
JSValue js_window_set_bordered(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowBordered(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Always on top getter/setter
|
||||
JSValue js_window_get_alwaysOnTop(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, flags & SDL_WINDOW_ALWAYS_ON_TOP);
|
||||
}
|
||||
|
||||
JSValue js_window_set_alwaysOnTop(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowAlwaysOnTop(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Fullscreen getter/setter
|
||||
JSValue js_window_get_fullscreen(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, flags & SDL_WINDOW_FULLSCREEN);
|
||||
}
|
||||
|
||||
JSValue js_window_set_fullscreen(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowFullscreen(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Focusable setter
|
||||
JSValue js_window_get_focusable(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, !(flags & SDL_WINDOW_NOT_FOCUSABLE));
|
||||
}
|
||||
|
||||
JSValue js_window_set_focusable(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowFocusable(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Modal setter
|
||||
JSValue js_window_get_modal(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, flags & SDL_WINDOW_MODAL);
|
||||
}
|
||||
|
||||
JSValue js_window_set_modal(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SetWindowModal(w, JS_ToBool(js,val));
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Hidden/visible state
|
||||
JSValue js_window_get_visible(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, !(flags & SDL_WINDOW_HIDDEN));
|
||||
}
|
||||
|
||||
JSValue js_window_set_visible(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
if (JS_ToBool(js,val))
|
||||
SDL_ShowWindow(w);
|
||||
else
|
||||
SDL_HideWindow(w);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Minimized state
|
||||
JSValue js_window_get_minimized(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, flags & SDL_WINDOW_MINIMIZED);
|
||||
}
|
||||
|
||||
JSValue js_window_set_minimized(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
if (JS_ToBool(js,val))
|
||||
SDL_MinimizeWindow(w);
|
||||
else
|
||||
SDL_RestoreWindow(w);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Maximized state
|
||||
JSValue js_window_get_maximized(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
return JS_NewBool(js, flags & SDL_WINDOW_MAXIMIZED);
|
||||
}
|
||||
|
||||
JSValue js_window_set_maximized(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
if (JS_ToBool(js,val))
|
||||
SDL_MaximizeWindow(w);
|
||||
else
|
||||
SDL_RestoreWindow(w);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// Other window methods
|
||||
JSValue js_window_raise(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_RaiseWindow(w);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_restore(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_RestoreWindow(w);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_flash(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_FlashOperation op = SDL_FLASH_BRIEFLY;
|
||||
if (argc > 0 && JS_IsString(argv[0])) {
|
||||
const char *operation = JS_ToCString(js,argv[0]);
|
||||
if (strcmp(operation, "cancel") == 0) op = SDL_FLASH_CANCEL;
|
||||
else if (strcmp(operation, "briefly") == 0) op = SDL_FLASH_BRIEFLY;
|
||||
else if (strcmp(operation, "until_focused") == 0) op = SDL_FLASH_UNTIL_FOCUSED;
|
||||
JS_FreeCString(js,operation);
|
||||
}
|
||||
SDL_FlashWindow(w, op);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_destroy(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_DestroyWindow(w);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_get_id(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
return number2js(js, SDL_GetWindowID(w));
|
||||
}
|
||||
|
||||
JSValue js_window_get_parent(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_Window *parent = SDL_GetWindowParent(w);
|
||||
if (!parent) return JS_NULL;
|
||||
return SDL_Window2js(js, parent);
|
||||
}
|
||||
|
||||
JSValue js_window_set_parent(JSContext *js, JSValue self, JSValue val)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_Window *parent = NULL;
|
||||
if (!JS_IsNull(val) && !JS_IsNull(val))
|
||||
parent = js2SDL_Window(js,val);
|
||||
SDL_SetWindowParent(w, parent);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_get_pixelDensity(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
return number2js(js, SDL_GetWindowPixelDensity(w));
|
||||
}
|
||||
|
||||
JSValue js_window_get_displayScale(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
return number2js(js, SDL_GetWindowDisplayScale(w));
|
||||
}
|
||||
|
||||
JSValue js_window_get_sizeInPixels(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
int width, height;
|
||||
SDL_GetWindowSizeInPixels(w, &width, &height);
|
||||
return vec22js(js, (HMM_Vec2){width,height});
|
||||
}
|
||||
|
||||
// Surface related
|
||||
JSValue js_window_get_surface(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_Surface *surf = SDL_GetWindowSurface(w);
|
||||
if (!surf) return JS_NULL;
|
||||
return SDL_Surface2js(js, surf);
|
||||
}
|
||||
|
||||
JSValue js_window_updateSurface(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
if (!SDL_UpdateWindowSurface(w))
|
||||
return JS_ThrowReferenceError(js, "Failed to update window surface: %s", SDL_GetError());
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_updateSurfaceRects(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
|
||||
if (!JS_IsArray(js, argv[0]))
|
||||
return JS_ThrowTypeError(js, "Expected array of rectangles");
|
||||
|
||||
int len = JS_ArrayLength(js, argv[0]);
|
||||
SDL_Rect rects[len];
|
||||
|
||||
for (int i = 0; i < len; i++) {
|
||||
JSValue val = JS_GetPropertyUint32(js, argv[0], i);
|
||||
rect r = js2rect(js, val);
|
||||
rects[i] = (SDL_Rect){r.x, r.y, r.w, r.h};
|
||||
JS_FreeValue(js, val);
|
||||
}
|
||||
|
||||
if (!SDL_UpdateWindowSurfaceRects(w, rects, len))
|
||||
return JS_ThrowReferenceError(js, "Failed to update window surface rects: %s", SDL_GetError());
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
JSValue js_window_get_flags(JSContext *js, JSValue self)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_WindowFlags flags = SDL_GetWindowFlags(w);
|
||||
|
||||
JSValue ret = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, ret, "fullscreen", JS_NewBool(js, flags & SDL_WINDOW_FULLSCREEN));
|
||||
JS_SetPropertyStr(js, ret, "opengl", JS_NewBool(js, flags & SDL_WINDOW_OPENGL));
|
||||
JS_SetPropertyStr(js, ret, "occluded", JS_NewBool(js, flags & SDL_WINDOW_OCCLUDED));
|
||||
JS_SetPropertyStr(js, ret, "hidden", JS_NewBool(js, flags & SDL_WINDOW_HIDDEN));
|
||||
JS_SetPropertyStr(js, ret, "borderless", JS_NewBool(js, flags & SDL_WINDOW_BORDERLESS));
|
||||
JS_SetPropertyStr(js, ret, "resizable", JS_NewBool(js, flags & SDL_WINDOW_RESIZABLE));
|
||||
JS_SetPropertyStr(js, ret, "minimized", JS_NewBool(js, flags & SDL_WINDOW_MINIMIZED));
|
||||
JS_SetPropertyStr(js, ret, "maximized", JS_NewBool(js, flags & SDL_WINDOW_MAXIMIZED));
|
||||
JS_SetPropertyStr(js, ret, "mouseGrabbed", JS_NewBool(js, flags & SDL_WINDOW_MOUSE_GRABBED));
|
||||
JS_SetPropertyStr(js, ret, "inputFocus", JS_NewBool(js, flags & SDL_WINDOW_INPUT_FOCUS));
|
||||
JS_SetPropertyStr(js, ret, "mouseFocus", JS_NewBool(js, flags & SDL_WINDOW_MOUSE_FOCUS));
|
||||
JS_SetPropertyStr(js, ret, "external", JS_NewBool(js, flags & SDL_WINDOW_EXTERNAL));
|
||||
JS_SetPropertyStr(js, ret, "modal", JS_NewBool(js, flags & SDL_WINDOW_MODAL));
|
||||
JS_SetPropertyStr(js, ret, "highPixelDensity", JS_NewBool(js, flags & SDL_WINDOW_HIGH_PIXEL_DENSITY));
|
||||
JS_SetPropertyStr(js, ret, "mouseCapture", JS_NewBool(js, flags & SDL_WINDOW_MOUSE_CAPTURE));
|
||||
JS_SetPropertyStr(js, ret, "mouseRelativeMode", JS_NewBool(js, flags & SDL_WINDOW_MOUSE_RELATIVE_MODE));
|
||||
JS_SetPropertyStr(js, ret, "alwaysOnTop", JS_NewBool(js, flags & SDL_WINDOW_ALWAYS_ON_TOP));
|
||||
JS_SetPropertyStr(js, ret, "utility", JS_NewBool(js, flags & SDL_WINDOW_UTILITY));
|
||||
JS_SetPropertyStr(js, ret, "tooltip", JS_NewBool(js, flags & SDL_WINDOW_TOOLTIP));
|
||||
JS_SetPropertyStr(js, ret, "popupMenu", JS_NewBool(js, flags & SDL_WINDOW_POPUP_MENU));
|
||||
JS_SetPropertyStr(js, ret, "keyboardGrabbed", JS_NewBool(js, flags & SDL_WINDOW_KEYBOARD_GRABBED));
|
||||
JS_SetPropertyStr(js, ret, "vulkan", JS_NewBool(js, flags & SDL_WINDOW_VULKAN));
|
||||
JS_SetPropertyStr(js, ret, "metal", JS_NewBool(js, flags & SDL_WINDOW_METAL));
|
||||
JS_SetPropertyStr(js, ret, "transparent", JS_NewBool(js, flags & SDL_WINDOW_TRANSPARENT));
|
||||
JS_SetPropertyStr(js, ret, "notFocusable", JS_NewBool(js, flags & SDL_WINDOW_NOT_FOCUSABLE));
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
JSValue js_window_sync(JSContext *js, JSValue self, int argc, JSValue *argv)
|
||||
{
|
||||
SDL_Window *w = js2SDL_Window(js,self);
|
||||
SDL_SyncWindow(w);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static const JSCFunctionListEntry js_SDL_Window_funcs[] = {
|
||||
MIST_FUNC_DEF(SDL_Window, fullscreen, 0),
|
||||
MIST_FUNC_DEF(SDL_Window, keyboard_shown, 0),
|
||||
MIST_FUNC_DEF(window, theme, 0),
|
||||
MIST_FUNC_DEF(window, safe_area, 0),
|
||||
MIST_FUNC_DEF(window, set_icon, 1),
|
||||
MIST_FUNC_DEF(window, raise, 0),
|
||||
MIST_FUNC_DEF(window, restore, 0),
|
||||
MIST_FUNC_DEF(window, flash, 1),
|
||||
MIST_FUNC_DEF(window, destroy, 0),
|
||||
MIST_FUNC_DEF(window, sync, 0),
|
||||
CGETSET_ADD(window, title),
|
||||
CGETSET_ADD(window, size),
|
||||
CGETSET_ADD(window, position),
|
||||
CGETSET_ADD(window, mouseGrab),
|
||||
CGETSET_ADD(window, keyboardGrab),
|
||||
CGETSET_ADD(window, opacity),
|
||||
CGETSET_ADD(window, minimumSize),
|
||||
CGETSET_ADD(window, maximumSize),
|
||||
CGETSET_ADD(window, resizable),
|
||||
CGETSET_ADD(window, bordered),
|
||||
CGETSET_ADD(window, alwaysOnTop),
|
||||
CGETSET_ADD(window, fullscreen),
|
||||
CGETSET_ADD(window, focusable),
|
||||
CGETSET_ADD(window, modal),
|
||||
CGETSET_ADD(window, visible),
|
||||
CGETSET_ADD(window, minimized),
|
||||
CGETSET_ADD(window, maximized),
|
||||
CGETSET_ADD(window, parent),
|
||||
JS_CGETSET_DEF("id", js_window_get_id, NULL),
|
||||
JS_CGETSET_DEF("pixelDensity", js_window_get_pixelDensity, NULL),
|
||||
JS_CGETSET_DEF("displayScale", js_window_get_displayScale, NULL),
|
||||
JS_CGETSET_DEF("sizeInPixels", js_window_get_sizeInPixels, NULL),
|
||||
JS_CGETSET_DEF("flags", js_window_get_flags, NULL),
|
||||
JS_CGETSET_DEF("surface", js_window_get_surface, NULL),
|
||||
MIST_FUNC_DEF(window, updateSurface, 0),
|
||||
MIST_FUNC_DEF(window, updateSurfaceRects, 1),
|
||||
};
|
||||
|
||||
// Cursor creation function
|
||||
JSC_CCALL(sdl_create_cursor,
|
||||
SDL_Surface *surf = js2SDL_Surface(js, argv[0]);
|
||||
if (!surf) return JS_ThrowReferenceError(js, "Invalid surface");
|
||||
|
||||
HMM_Vec2 hot = {0, 0};
|
||||
if (argc > 1) hot = js2vec2(js, argv[1]);
|
||||
|
||||
SDL_Cursor *cursor = SDL_CreateColorCursor(surf, hot.x, hot.y);
|
||||
if (!cursor) return JS_ThrowReferenceError(js, "Failed to create cursor: %s", SDL_GetError());
|
||||
|
||||
return SDL_Cursor2js(js, cursor);
|
||||
)
|
||||
|
||||
// Set cursor function
|
||||
JSC_CCALL(sdl_set_cursor,
|
||||
SDL_Cursor *cursor = js2SDL_Cursor(js, argv[0]);
|
||||
|
||||
if (!cursor) return JS_ThrowReferenceError(js, "Invalid cursor");
|
||||
|
||||
SDL_SetCursor(cursor);
|
||||
)
|
||||
|
||||
JSValue js_sdl_video_use(JSContext *js) {
|
||||
if (!SDL_Init(SDL_INIT_VIDEO))
|
||||
return JS_ThrowInternalError(js, "Unable to initialize video subsystem: %s", SDL_GetError());
|
||||
|
||||
JSValue ret = JS_NewObject(js);
|
||||
|
||||
// Initialize classes
|
||||
QJSCLASSPREP_FUNCS(SDL_Window)
|
||||
QJSCLASSPREP_NO_FUNCS(SDL_Cursor)
|
||||
|
||||
// Create window constructor
|
||||
JSValue window_ctor = JS_NewCFunction2(js, js_window_constructor, "window", 1, JS_CFUNC_constructor, 0);
|
||||
|
||||
// Set prototype on constructor
|
||||
JS_SetConstructor(js, window_ctor, SDL_Window_proto);
|
||||
|
||||
// Set constructors in endowments
|
||||
JS_SetPropertyStr(js, ret, "window", window_ctor);
|
||||
|
||||
// Add cursor functions
|
||||
JS_SetPropertyStr(js, ret, "createCursor",
|
||||
JS_NewCFunction(js, js_sdl_create_cursor, "createCursor", 2));
|
||||
JS_SetPropertyStr(js, ret, "setCursor",
|
||||
JS_NewCFunction(js, js_sdl_set_cursor, "setCursor", 1));
|
||||
|
||||
return ret;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
#include "qjs_macros.h"
|
||||
#include "jsffi.h"
|
||||
#include "spline.h"
|
||||
#include "HandmadeMath.h"
|
||||
#include "stb_ds.h"
|
||||
|
||||
// Helper functions - these are duplicated from jsffi.c as they're used there too
|
||||
static HMM_Vec2 *js2cpvec2arr(JSContext *js, JSValue v) {
|
||||
HMM_Vec2 *arr = NULL;
|
||||
int n = JS_ArrayLength(js, v);
|
||||
arrsetlen(arr, n);
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
arr[i] = js2vec2(js, JS_GetPropertyUint32(js, v, i));
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
static JSValue vecarr2js(JSContext *js, HMM_Vec2 *points, int n) {
|
||||
JSValue array = JS_NewArray(js);
|
||||
for (int i = 0; i < n; i++)
|
||||
JS_SetPropertyUint32(js, array, i, vec22js(js, points[i]));
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
JSC_CCALL(spline_catmull,
|
||||
HMM_Vec2 *points = js2cpvec2arr(js, argv[0]);
|
||||
float param = js2number(js, argv[1]);
|
||||
HMM_Vec2 *samples = catmull_rom_ma_v2(points, param);
|
||||
|
||||
if (!samples)
|
||||
ret = JS_NULL;
|
||||
else
|
||||
ret = vecarr2js(js, samples, arrlen(samples));
|
||||
|
||||
arrfree(points);
|
||||
arrfree(samples);
|
||||
)
|
||||
|
||||
JSC_CCALL(spline_bezier,
|
||||
HMM_Vec2 *points = js2cpvec2arr(js, argv[0]);
|
||||
float param = js2number(js, argv[1]);
|
||||
HMM_Vec2 *samples = bezier_cb_ma_v2(points, param);
|
||||
|
||||
if (!samples)
|
||||
ret = JS_NULL;
|
||||
else
|
||||
ret = vecarr2js(js, samples, arrlen(samples));
|
||||
|
||||
arrfree(samples);
|
||||
arrfree(points);
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_spline_funcs[] = {
|
||||
MIST_FUNC_DEF(spline, catmull, 2),
|
||||
MIST_FUNC_DEF(spline, bezier, 2)
|
||||
};
|
||||
|
||||
JSValue js_spline_use(JSContext *js) {
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, mod, js_spline_funcs, countof(js_spline_funcs));
|
||||
return mod;
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
#include "qjs_sprite.h"
|
||||
#include "jsffi.h"
|
||||
#include "qjs_macros.h"
|
||||
|
||||
#include "sprite.h"
|
||||
#include "HandmadeMath.h"
|
||||
|
||||
// Sprite class definitions
|
||||
static JSClassID js_sprite_id;
|
||||
static void js_sprite_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) {
|
||||
sprite *sp = JS_GetOpaque(val, js_sprite_id);
|
||||
if (!sp) return;
|
||||
JS_MarkValue(rt, sp->image, mark_func);
|
||||
}
|
||||
|
||||
// Class definition for sprite with mark function for GC
|
||||
QJSCLASSMARK(sprite,)
|
||||
|
||||
// SPRITE GETTER/SETTER FUNCTIONS
|
||||
JSC_GETSET(sprite, pos, vec2)
|
||||
JSC_GETSET(sprite, center, vec2)
|
||||
JSC_GETSET(sprite, layer, number)
|
||||
JSC_GETSET(sprite, color, color)
|
||||
JSC_GETSET(sprite, skew, vec2)
|
||||
JSC_GETSET(sprite, scale, vec2)
|
||||
JSC_GETSET(sprite, rotation, number)
|
||||
|
||||
// SPRITE ACTION FUNCTIONS
|
||||
|
||||
JSC_CCALL(sprite_move,
|
||||
sprite *sp = js2sprite(js,self);
|
||||
HMM_Vec2 mv = js2vec2(js,argv[0]);
|
||||
sp->pos.x += mv.x;
|
||||
sp->pos.y += mv.y;
|
||||
)
|
||||
|
||||
JSC_CCALL(sprite_set_affine,
|
||||
sprite *sp = js2sprite(js,self);
|
||||
sprite_apply(sp);
|
||||
)
|
||||
|
||||
JSC_CCALL(sprite_set_image,
|
||||
sprite *sp = js2sprite(js,self);
|
||||
if (!JS_IsNull(sp->image))
|
||||
JS_FreeValue(js,sp->image);
|
||||
sp->image = JS_DupValue(js, argv[0]);
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_sprite_funcs[] = {
|
||||
MIST_FUNC_DEF(sprite, set_affine, 0),
|
||||
MIST_FUNC_DEF(sprite, set_image, 1),
|
||||
MIST_FUNC_DEF(sprite, move, 1),
|
||||
JS_CGETSET_DEF("pos", js_sprite_get_pos, js_sprite_set_pos),
|
||||
JS_CGETSET_DEF("scale", js_sprite_get_scale, js_sprite_set_scale),
|
||||
JS_CGETSET_DEF("skew", js_sprite_get_skew, js_sprite_set_skew),
|
||||
JS_CGETSET_DEF("layer", js_sprite_get_layer, js_sprite_set_layer),
|
||||
JS_CGETSET_DEF("color", js_sprite_get_color, js_sprite_set_color),
|
||||
JS_CGETSET_DEF("center", js_sprite_get_center, js_sprite_set_center),
|
||||
JS_CGETSET_DEF("rotation", js_sprite_get_rotation, js_sprite_set_rotation),
|
||||
};
|
||||
|
||||
// Constructor function for sprite
|
||||
static JSValue js_sprite_constructor(JSContext *js, JSValueConst new_target, int argc, JSValueConst *argv) {
|
||||
sprite *sp = make_sprite();
|
||||
if (!sp) return JS_ThrowOutOfMemory(js);
|
||||
|
||||
// If an options object is provided, initialize the sprite with it
|
||||
if (argc > 0 && JS_IsObject(argv[0])) {
|
||||
JS_GETATOM(js, sp->pos, argv[0], pos, vec2)
|
||||
JS_GETATOM(js, sp->center, argv[0], center, vec2)
|
||||
JS_GETATOM(js, sp->skew, argv[0], skew, vec2)
|
||||
JS_GETATOM(js, sp->scale, argv[0], scale, vec2)
|
||||
JS_GETATOM(js, sp->rotation, argv[0], rotation, number)
|
||||
JS_GETATOM(js, sp->layer, argv[0], layer, number)
|
||||
JS_GETATOM(js, sp->color, argv[0], color, color)
|
||||
|
||||
JSValue image = JS_GetProperty(js, argv[0], JS_NewAtom(js, "image"));
|
||||
if (!JS_IsNull(image)) {
|
||||
sp->image = image; // Transfer ownership, no need to dup
|
||||
}
|
||||
}
|
||||
|
||||
// Default values if not provided
|
||||
if (sp->scale.x == 0 && sp->scale.y == 0) {
|
||||
sp->scale.x = 1;
|
||||
sp->scale.y = 1;
|
||||
}
|
||||
if (sp->color.w == 0) sp->color.w = 1; // Default alpha to 1
|
||||
|
||||
sprite_apply(sp);
|
||||
return sprite2js(js, sp);
|
||||
}
|
||||
|
||||
JSValue js_sprite_use(JSContext *js) {
|
||||
// Register the sprite class
|
||||
QJSCLASSPREP_FUNCS(sprite);
|
||||
|
||||
// Create the constructor function
|
||||
JSValue ctor = JS_NewCFunction2(js, js_sprite_constructor, "sprite", 1, JS_CFUNC_constructor, 0);
|
||||
|
||||
// Set the prototype on the constructor
|
||||
JSValue proto = JS_GetClassProto(js, js_sprite_id);
|
||||
JS_SetConstructor(js, ctor, proto);
|
||||
JS_FreeValue(js, proto);
|
||||
|
||||
return ctor;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
#ifndef QJS_SPRITE_H
|
||||
#define QJS_SPRITE_H
|
||||
|
||||
#include "cell.h"
|
||||
|
||||
#include "sprite.h"
|
||||
|
||||
JSValue js_sprite_use(JSContext *ctx);
|
||||
|
||||
sprite *js2sprite(JSContext *js, JSValue v);
|
||||
|
||||
#endif /* QJS_SPRITE_H */
|
||||
@@ -1,146 +0,0 @@
|
||||
#include "font.h"
|
||||
#include "qjs_macros.h"
|
||||
#include "HandmadeMath.h"
|
||||
#include "render.h"
|
||||
#include "stb_ds.h"
|
||||
#include "cell.h"
|
||||
#include "qjs_sdl.h"
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
// External functions from jsffi.c
|
||||
typedef HMM_Vec4 colorf;
|
||||
extern colorf js2color(JSContext *js, JSValue v);
|
||||
extern JSValue vec22js(JSContext *js, HMM_Vec2 v);
|
||||
extern HMM_Vec2 js2vec2(JSContext *js, JSValue v);
|
||||
extern rect js2rect(JSContext *js, JSValue v);
|
||||
extern double js2number(JSContext *js, JSValue v);
|
||||
extern JSValue number2js(JSContext *js, double g);
|
||||
extern void *js_get_blob_data(JSContext *js, size_t *len, JSValue v);
|
||||
extern JSValue js_new_blob_stoned_copy(JSContext *js, void *data, size_t size);
|
||||
extern JSValue quads_to_mesh(JSContext *js, text_vert *buffer);
|
||||
extern int uncaught_exception(JSContext *js, JSValue ret);
|
||||
|
||||
// QuickJS class for font
|
||||
QJSCLASS(font,)
|
||||
|
||||
// Font constructor
|
||||
JSC_CCALL(staef_font_new,
|
||||
size_t len;
|
||||
void *data = js_get_blob_data(js, &len, argv[0]);
|
||||
if (!data) return JS_ThrowReferenceError(js, "could not get array buffer data");
|
||||
|
||||
double height = js2number(js, argv[1]);
|
||||
font *f = MakeFont(data, len, (int)height);
|
||||
if (!f) return JS_ThrowReferenceError(js, "could not create font");
|
||||
|
||||
ret = font2js(js, f);
|
||||
|
||||
// Create surface data object for the font's atlas
|
||||
if (f->surface) {
|
||||
JSValue surfData = JS_NewObject(js);
|
||||
JS_SetPropertyStr(js, surfData, "width", JS_NewInt32(js, f->surface->w));
|
||||
JS_SetPropertyStr(js, surfData, "height", JS_NewInt32(js, f->surface->h));
|
||||
JS_SetPropertyStr(js, surfData, "format", pixelformat2js(js, f->surface->format));
|
||||
JS_SetPropertyStr(js, surfData, "pitch", JS_NewInt32(js, f->surface->pitch));
|
||||
|
||||
// Lock surface if needed
|
||||
int locked = 0;
|
||||
if (SDL_MUSTLOCK(f->surface)) {
|
||||
if (SDL_LockSurface(f->surface) < 0)
|
||||
return JS_ThrowInternalError(js, "Lock surface failed: %s", SDL_GetError());
|
||||
locked = 1;
|
||||
}
|
||||
|
||||
size_t byte_size = f->surface->pitch * f->surface->h;
|
||||
JS_SetPropertyStr(js, surfData, "pixels", js_new_blob_stoned_copy(js, f->surface->pixels, byte_size));
|
||||
|
||||
if (locked)
|
||||
SDL_UnlockSurface(f->surface);
|
||||
|
||||
JS_SetPropertyStr(js, ret, "surface", surfData);
|
||||
}
|
||||
)
|
||||
|
||||
// Calculate text size
|
||||
JSC_CCALL(staef_font_text_size,
|
||||
font *f = js2font(js, self);
|
||||
const char *str = JS_ToCString(js, argv[0]);
|
||||
float letterSpacing = argc > 1 ? js2number(js, argv[1]) : 0;
|
||||
float wrap = argc > 2 ? js2number(js, argv[2]) : -1;
|
||||
const char *breakat = argc > 3 ? JS_ToCString(js, argv[3]) : NULL;
|
||||
int breakAt = (breakat == "character") ? CHARACTER : WORD;
|
||||
const char *align = argc > 4 ? JS_ToCString(js, argv[4]) : NULL;
|
||||
int alignAt = (align == "right") ? RIGHT : (align == "center") ? CENTER : (align == "justify") ? JUSTIFY : LEFT;
|
||||
ret = vec22js(js, measure_text(str, f, letterSpacing, wrap, breakAt, alignAt));
|
||||
JS_FreeCString(js, str);
|
||||
if (breakat) JS_FreeCString(js, breakat);
|
||||
if (align) JS_FreeCString(js, align);
|
||||
)
|
||||
|
||||
// Generate text buffer (mesh data)
|
||||
JSC_CCALL(staef_font_make_text_buffer,
|
||||
font *f = js2font(js, self);
|
||||
const char *s = JS_ToCString(js, argv[0]);
|
||||
rect rectpos = js2rect(js, argv[1]);
|
||||
colorf c = js2color(js, argv[2]);
|
||||
float wrap = argc > 3 ? js2number(js, argv[3]) : -1;
|
||||
const char *breakat = argc > 4 ? JS_ToCString(js, argv[4]) : NULL;
|
||||
int breakAt = (breakat == "character") ? CHARACTER : WORD;
|
||||
const char *align = argc > 5 ? JS_ToCString(js, argv[5]) : NULL;
|
||||
int alignAt = (align == "right") ? RIGHT : (align == "center") ? CENTER : (align == "justify") ? JUSTIFY : LEFT;
|
||||
|
||||
HMM_Vec2 startpos = {.x = rectpos.x, .y = rectpos.y };
|
||||
text_vert *buffer = renderText(s, startpos, f, c, wrap, breakAt, alignAt, 0);
|
||||
ret = quads_to_mesh(js, buffer);
|
||||
JS_FreeCString(js, s);
|
||||
if (breakat) JS_FreeCString(js, breakat);
|
||||
if (align) JS_FreeCString(js, align);
|
||||
arrfree(buffer);
|
||||
)
|
||||
|
||||
// Font property getters/setters
|
||||
JSC_GETSET(font, linegap, number)
|
||||
JSC_GETSET(font, ascent, number)
|
||||
JSC_GETSET(font, descent, number)
|
||||
JSC_GETSET(font, line_height, number)
|
||||
JSC_GETSET(font, height, number)
|
||||
|
||||
// Font methods
|
||||
static const JSCFunctionListEntry js_font_funcs[] = {
|
||||
MIST_FUNC_DEF(staef_font, text_size, 5),
|
||||
MIST_FUNC_DEF(staef_font, make_text_buffer, 6),
|
||||
CGETSET_ADD(font, linegap),
|
||||
CGETSET_ADD(font, ascent),
|
||||
CGETSET_ADD(font, descent),
|
||||
CGETSET_ADD(font, line_height),
|
||||
CGETSET_ADD(font, height),
|
||||
};
|
||||
|
||||
// Font constructor function
|
||||
static JSValue js_font_constructor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv)
|
||||
{
|
||||
return js_staef_font_new(ctx, JS_NULL, argc, argv);
|
||||
}
|
||||
|
||||
// Initialize the staef module
|
||||
JSValue js_staef_use(JSContext *js)
|
||||
{
|
||||
JSValue mod = JS_NewObject(js);
|
||||
JSValue proto;
|
||||
|
||||
// Initialize font class
|
||||
JS_NewClassID(&js_font_id);
|
||||
JS_NewClass(JS_GetRuntime(js), js_font_id, &js_font_class);
|
||||
proto = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, proto, js_font_funcs, countof(js_font_funcs));
|
||||
JS_SetClassProto(js, js_font_id, proto);
|
||||
|
||||
// Create font constructor
|
||||
JSValue font_ctor = JS_NewCFunction2(js, js_font_constructor, "font", 2, JS_CFUNC_constructor, 0);
|
||||
JS_SetConstructor(js, font_ctor, proto);
|
||||
|
||||
// Add font constructor to module (lowercase to match "new staef.font")
|
||||
JS_SetPropertyStr(js, mod, "font", font_ctor);
|
||||
|
||||
return mod;
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
#include "jsffi.h"
|
||||
#include "qjs_macros.h"
|
||||
#include "stb_ds.h"
|
||||
|
||||
#include "transform.h"
|
||||
#include "HandmadeMath.h"
|
||||
#include "cell.h"
|
||||
|
||||
// Transform class definitions
|
||||
JSClassID js_transform_id;
|
||||
static void js_transform_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) {
|
||||
transform *t = JS_GetOpaque(val, js_transform_id);
|
||||
if (!t) return;
|
||||
// Mark the JSValue references stored in your struct
|
||||
JS_MarkValue(rt, t->change_hook, mark_func);
|
||||
JS_MarkValue(rt, t->jsparent, mark_func);
|
||||
// Mark the array elements
|
||||
for (int i = 0; i < arrlen(t->jschildren); i++)
|
||||
JS_MarkValue(rt, t->jschildren[i], mark_func);
|
||||
}
|
||||
|
||||
QJSCLASSMARK_EXTERN(transform,)
|
||||
|
||||
// TRANSFORM GETTER/SETTER FUNCTIONS
|
||||
JSC_GETSET_APPLY(transform, pos, vec3)
|
||||
JSC_GETSET_APPLY(transform, scale, vec3)
|
||||
JSC_GETSET_APPLY(transform, rotation, quat)
|
||||
|
||||
static JSValue js_transform_get_change_hook(JSContext *js, JSValueConst self)
|
||||
{
|
||||
transform *t = js2transform(js,self);
|
||||
return JS_DupValue(js,t->change_hook);
|
||||
}
|
||||
|
||||
static JSValue js_transform_set_change_hook(JSContext *js, JSValueConst self, JSValue v)
|
||||
{
|
||||
transform *t = js2transform(js,self);
|
||||
if (!JS_IsNull(v) && !JS_IsFunction(js,v)) return JS_ThrowReferenceError(js, "Hook must be a function.");
|
||||
JS_FreeValue(js,t->change_hook);
|
||||
t->change_hook = JS_DupValue(js,v);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_transform_get_parent(JSContext *js, JSValueConst self)
|
||||
{
|
||||
transform *t = js2transform(js,self);
|
||||
if (t->parent) return JS_DupValue(js,t->jsparent);
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
static JSValue js_transform_set_parent(JSContext *js, JSValueConst self, JSValue v)
|
||||
{
|
||||
transform *p = js2transform(js,v);
|
||||
if (!JS_IsNull(v) && !p)
|
||||
return JS_ThrowReferenceError(js,"Parent must be another transform.");
|
||||
|
||||
transform *t = js2transform(js,self);
|
||||
|
||||
if (t == p)
|
||||
return JS_ThrowReferenceError(js, "A transform cannot be its own parent.");
|
||||
|
||||
if (t->parent) {
|
||||
transform *cur_parent = t->parent;
|
||||
JS_FreeValue(js,t->jsparent);
|
||||
t->jsparent = JS_NULL;
|
||||
|
||||
for (int i = 0; i < arrlen(cur_parent->children); i++) {
|
||||
if (cur_parent->children[i] == t) {
|
||||
arrdelswap(cur_parent->children,i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < arrlen(cur_parent->jschildren); i++) {
|
||||
if (JS_SameValue(js,cur_parent->jschildren[i],self)) {
|
||||
JS_FreeValue(js,cur_parent->jschildren[i]);
|
||||
arrdelswap(cur_parent->jschildren,i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t->parent = p;
|
||||
t->jsparent = JS_DupValue(js,v);
|
||||
|
||||
if (p) {
|
||||
arrput(p->children, t);
|
||||
JSValue child = JS_DupValue(js,self);
|
||||
arrput(p->jschildren,child);
|
||||
}
|
||||
|
||||
transform_apply(t);
|
||||
|
||||
return JS_NULL;
|
||||
}
|
||||
|
||||
// TRANSFORM ACTION FUNCTIONS
|
||||
|
||||
JSC_CCALL(transform_move,
|
||||
transform *t = js2transform(js,self);
|
||||
transform_move(t, js2vec3(js,argv[0]));
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_lookat,
|
||||
HMM_Vec3 point = js2vec3(js,argv[0]);
|
||||
transform *go = js2transform(js,self);
|
||||
HMM_Mat4 m = HMM_LookAt_RH(go->pos, point, vUP);
|
||||
go->rotation = HMM_M4ToQ_RH(m);
|
||||
transform_apply(go);
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_rotate,
|
||||
HMM_Vec3 axis = js2vec3(js,argv[0]);
|
||||
transform *t = js2transform(js,self);
|
||||
HMM_Quat rot = HMM_QFromAxisAngle_RH(axis, js2angle(js,argv[1]));
|
||||
t->rotation = HMM_MulQ(t->rotation,rot);
|
||||
transform_apply(t);
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_angle,
|
||||
HMM_Vec3 axis = js2vec3(js,argv[0]);
|
||||
transform *t = js2transform(js,self);
|
||||
if (axis.x) return angle2js(js,HMM_Q_Roll(t->rotation));
|
||||
if (axis.y) return angle2js(js,HMM_Q_Pitch(t->rotation));
|
||||
if (axis.z) return angle2js(js,HMM_Q_Yaw(t->rotation));
|
||||
return angle2js(js,0);
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_direction,
|
||||
transform *t = js2transform(js,self);
|
||||
return vec32js(js, HMM_QVRot(js2vec3(js,argv[0]), t->rotation));
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_phys2d,
|
||||
transform *t = js2transform(js,self);
|
||||
HMM_Vec2 v = js2vec2(js,argv[0]);
|
||||
float av = js2number(js,argv[1]);
|
||||
float dt = js2number(js,argv[2]);
|
||||
transform_move(t, (HMM_Vec3){v.x*dt,v.y*dt,0});
|
||||
HMM_Quat rot = HMM_QFromAxisAngle_RH((HMM_Vec3){0,0,1}, av*dt);
|
||||
t->rotation = HMM_MulQ(t->rotation, rot);
|
||||
transform_apply(t);
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_unit,
|
||||
transform *t = js2transform(js,self);
|
||||
t->pos = v3zero;
|
||||
t->rotation = QUAT1;
|
||||
t->scale = v3one;
|
||||
transform_apply(t);
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_trs,
|
||||
transform *t = js2transform(js,self);
|
||||
t->pos = JS_IsNull(argv[0]) ? v3zero : js2vec3(js,argv[0]);
|
||||
t->rotation = JS_IsNull(argv[1]) ? QUAT1 : js2quat(js,argv[1]);
|
||||
t->scale = JS_IsNull(argv[2]) ? v3one : js2vec3(js,argv[2]);
|
||||
transform_apply(t);
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_rect,
|
||||
transform *t = js2transform(js,self);
|
||||
rect r = js2rect(js,argv[0]);
|
||||
t->pos = (HMM_Vec3){r.x,r.y,0};
|
||||
t->scale = (HMM_Vec3){r.w,r.h,1};
|
||||
t->rotation = QUAT1;
|
||||
transform_apply(t);
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_array,
|
||||
transform *t = js2transform(js,self);
|
||||
HMM_Mat4 m= transform2mat(t);
|
||||
ret = JS_NewArray(js);
|
||||
for (int i = 0; i < 16; i++)
|
||||
JS_SetPropertyUint32(js,ret,i, number2js(js,m.em[i]));
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_torect,
|
||||
transform *t = js2transform(js,self);
|
||||
return rect2js(js,transform2rect(t));
|
||||
)
|
||||
|
||||
JSC_CCALL(transform_children,
|
||||
transform *t = js2transform(js,self);
|
||||
ret = JS_NewArray(js);
|
||||
for (int i = 0; i < arrlen(t->jschildren); i++)
|
||||
JS_SetPropertyUint32(js,ret,i,JS_DupValue(js,t->jschildren[i]));
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_transform_funcs[] = {
|
||||
CGETSET_ADD(transform, pos),
|
||||
CGETSET_ADD(transform, scale),
|
||||
CGETSET_ADD(transform, rotation),
|
||||
CGETSET_ADD(transform, parent),
|
||||
CGETSET_ADD(transform, change_hook),
|
||||
MIST_FUNC_DEF(transform, trs, 3),
|
||||
MIST_FUNC_DEF(transform, phys2d, 3),
|
||||
MIST_FUNC_DEF(transform, move, 1),
|
||||
MIST_FUNC_DEF(transform, rotate, 2),
|
||||
MIST_FUNC_DEF(transform, angle, 1),
|
||||
MIST_FUNC_DEF(transform, lookat, 1),
|
||||
MIST_FUNC_DEF(transform, direction, 1),
|
||||
MIST_FUNC_DEF(transform, unit, 0),
|
||||
MIST_FUNC_DEF(transform, rect, 1),
|
||||
MIST_FUNC_DEF(transform, array, 0),
|
||||
MIST_FUNC_DEF(transform, torect, 0),
|
||||
MIST_FUNC_DEF(transform, children, 0),
|
||||
};
|
||||
|
||||
// Constructor function for transform
|
||||
static JSValue js_transform_constructor(JSContext *js, JSValueConst new_target, int argc, JSValueConst *argv) {
|
||||
transform *t = make_transform();
|
||||
if (!t) return JS_ThrowOutOfMemory(js);
|
||||
|
||||
JSValue ret = transform2js(js, t);
|
||||
t->self = ret;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
JSC_CCALL(transform_clean,
|
||||
clean_all(js);
|
||||
)
|
||||
|
||||
static const JSCFunctionListEntry js_transform_ctor_funcs[] = {
|
||||
MIST_FUNC_DEF(transform, clean, 0),
|
||||
};
|
||||
|
||||
JSValue js_transform_use(JSContext *js) {
|
||||
// Register the transform class
|
||||
QJSCLASSPREP_FUNCS(transform);
|
||||
|
||||
// Create the constructor function
|
||||
JSValue ctor = JS_NewCFunction2(js, js_transform_constructor, "transform", 0, JS_CFUNC_constructor, 0);
|
||||
|
||||
// Set the prototype on the constructor
|
||||
JSValue proto = JS_GetClassProto(js, js_transform_id);
|
||||
JS_SetConstructor(js, ctor, proto);
|
||||
JS_FreeValue(js, proto);
|
||||
|
||||
// Add static methods to the constructor
|
||||
JS_SetPropertyFunctionList(js, ctor, js_transform_ctor_funcs, countof(js_transform_ctor_funcs));
|
||||
|
||||
return ctor;
|
||||
}
|
||||
742
source/qoa.h
742
source/qoa.h
@@ -1,742 +0,0 @@
|
||||
/*
|
||||
|
||||
Copyright (c) 2023, Dominic Szablewski - https://phoboslab.org
|
||||
SPDX-License-Identifier: MIT
|
||||
|
||||
QOA - The "Quite OK Audio" format for fast, lossy audio compression
|
||||
|
||||
|
||||
-- Data Format
|
||||
|
||||
QOA encodes pulse-code modulated (PCM) audio data with up to 255 channels,
|
||||
sample rates from 1 up to 16777215 hertz and a bit depth of 16 bits.
|
||||
|
||||
The compression method employed in QOA is lossy; it discards some information
|
||||
from the uncompressed PCM data. For many types of audio signals this compression
|
||||
is "transparent", i.e. the difference from the original file is often not
|
||||
audible.
|
||||
|
||||
QOA encodes 20 samples of 16 bit PCM data into slices of 64 bits. A single
|
||||
sample therefore requires 3.2 bits of storage space, resulting in a 5x
|
||||
compression (16 / 3.2).
|
||||
|
||||
A QOA file consists of an 8 byte file header, followed by a number of frames.
|
||||
Each frame contains an 8 byte frame header, the current 16 byte en-/decoder
|
||||
state per channel and 256 slices per channel. Each slice is 8 bytes wide and
|
||||
encodes 20 samples of audio data.
|
||||
|
||||
All values, including the slices, are big endian. The file layout is as follows:
|
||||
|
||||
struct {
|
||||
struct {
|
||||
char magic[4]; // magic bytes "qoaf"
|
||||
uint32_t samples; // samples per channel in this file
|
||||
} file_header;
|
||||
|
||||
struct {
|
||||
struct {
|
||||
uint8_t num_channels; // no. of channels
|
||||
uint24_t samplerate; // samplerate in hz
|
||||
uint16_t fsamples; // samples per channel in this frame
|
||||
uint16_t fsize; // frame size (includes this header)
|
||||
} frame_header;
|
||||
|
||||
struct {
|
||||
int16_t history[4]; // most recent last
|
||||
int16_t weights[4]; // most recent last
|
||||
} lms_state[num_channels];
|
||||
|
||||
qoa_slice_t slices[256][num_channels];
|
||||
|
||||
} frames[ceil(samples / (256 * 20))];
|
||||
} qoa_file_t;
|
||||
|
||||
Each `qoa_slice_t` contains a quantized scalefactor `sf_quant` and 20 quantized
|
||||
residuals `qrNN`:
|
||||
|
||||
.- QOA_SLICE -- 64 bits, 20 samples --------------------------/ /------------.
|
||||
| Byte[0] | Byte[1] | Byte[2] \ \ Byte[7] |
|
||||
| 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 / / 2 1 0 |
|
||||
|------------+--------+--------+--------+---------+---------+-\ \--+---------|
|
||||
| sf_quant | qr00 | qr01 | qr02 | qr03 | qr04 | / / | qr19 |
|
||||
`-------------------------------------------------------------\ \------------`
|
||||
|
||||
Each frame except the last must contain exactly 256 slices per channel. The last
|
||||
frame may contain between 1 .. 256 (inclusive) slices per channel. The last
|
||||
slice (for each channel) in the last frame may contain less than 20 samples; the
|
||||
slice still must be 8 bytes wide, with the unused samples zeroed out.
|
||||
|
||||
Channels are interleaved per slice. E.g. for 2 channel stereo:
|
||||
slice[0] = L, slice[1] = R, slice[2] = L, slice[3] = R ...
|
||||
|
||||
A valid QOA file or stream must have at least one frame. Each frame must contain
|
||||
at least one channel and one sample with a samplerate between 1 .. 16777215
|
||||
(inclusive).
|
||||
|
||||
If the total number of samples is not known by the encoder, the samples in the
|
||||
file header may be set to 0x00000000 to indicate that the encoder is
|
||||
"streaming". In a streaming context, the samplerate and number of channels may
|
||||
differ from frame to frame. For static files (those with samples set to a
|
||||
non-zero value), each frame must have the same number of channels and same
|
||||
samplerate.
|
||||
|
||||
Note that this implementation of QOA only handles files with a known total
|
||||
number of samples.
|
||||
|
||||
A decoder should support at least 8 channels. The channel layout for channel
|
||||
counts 1 .. 8 is:
|
||||
|
||||
1. Mono
|
||||
2. L, R
|
||||
3. L, R, C
|
||||
4. FL, FR, B/SL, B/SR
|
||||
5. FL, FR, C, B/SL, B/SR
|
||||
6. FL, FR, C, LFE, B/SL, B/SR
|
||||
7. FL, FR, C, LFE, B, SL, SR
|
||||
8. FL, FR, C, LFE, BL, BR, SL, SR
|
||||
|
||||
QOA predicts each audio sample based on the previously decoded ones using a
|
||||
"Sign-Sign Least Mean Squares Filter" (LMS). This prediction plus the
|
||||
dequantized residual forms the final output sample.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
Header - Public functions */
|
||||
|
||||
#ifndef QOA_H
|
||||
#define QOA_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define QOA_MIN_FILESIZE 16
|
||||
#define QOA_MAX_CHANNELS 8
|
||||
|
||||
#define QOA_SLICE_LEN 20
|
||||
#define QOA_SLICES_PER_FRAME 256
|
||||
#define QOA_FRAME_LEN (QOA_SLICES_PER_FRAME * QOA_SLICE_LEN)
|
||||
#define QOA_LMS_LEN 4
|
||||
#define QOA_MAGIC 0x716f6166 /* 'qoaf' */
|
||||
|
||||
#define QOA_FRAME_SIZE(channels, slices) \
|
||||
(8 + QOA_LMS_LEN * 4 * channels + 8 * slices * channels)
|
||||
|
||||
typedef struct {
|
||||
int history[QOA_LMS_LEN];
|
||||
int weights[QOA_LMS_LEN];
|
||||
} qoa_lms_t;
|
||||
|
||||
typedef struct {
|
||||
unsigned int channels;
|
||||
unsigned int samplerate;
|
||||
unsigned int samples;
|
||||
qoa_lms_t lms[QOA_MAX_CHANNELS];
|
||||
#ifdef QOA_RECORD_TOTAL_ERROR
|
||||
double error;
|
||||
#endif
|
||||
} qoa_desc;
|
||||
|
||||
unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes);
|
||||
unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes);
|
||||
void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len);
|
||||
|
||||
unsigned int qoa_max_frame_size(qoa_desc *qoa);
|
||||
unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa);
|
||||
unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len);
|
||||
short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *file);
|
||||
|
||||
#ifndef QOA_NO_STDIO
|
||||
|
||||
int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa);
|
||||
void *qoa_read(const char *filename, qoa_desc *qoa);
|
||||
|
||||
#endif /* QOA_NO_STDIO */
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif /* QOA_H */
|
||||
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
Implementation */
|
||||
|
||||
#ifdef QOA_IMPLEMENTATION
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifndef QOA_MALLOC
|
||||
#define QOA_MALLOC(sz) malloc(sz)
|
||||
#define QOA_FREE(p) free(p)
|
||||
#endif
|
||||
|
||||
typedef unsigned long long qoa_uint64_t;
|
||||
|
||||
|
||||
/* The quant_tab provides an index into the dequant_tab for residuals in the
|
||||
range of -8 .. 8. It maps this range to just 3bits and becomes less accurate at
|
||||
the higher end. Note that the residual zero is identical to the lowest positive
|
||||
value. This is mostly fine, since the qoa_div() function always rounds away
|
||||
from zero. */
|
||||
|
||||
static const int qoa_quant_tab[17] = {
|
||||
7, 7, 7, 5, 5, 3, 3, 1, /* -8..-1 */
|
||||
0, /* 0 */
|
||||
0, 2, 2, 4, 4, 6, 6, 6 /* 1.. 8 */
|
||||
};
|
||||
|
||||
|
||||
/* We have 16 different scalefactors. Like the quantized residuals these become
|
||||
less accurate at the higher end. In theory, the highest scalefactor that we
|
||||
would need to encode the highest 16bit residual is (2**16)/8 = 8192. However we
|
||||
rely on the LMS filter to predict samples accurately enough that a maximum
|
||||
residual of one quarter of the 16 bit range is sufficient. I.e. with the
|
||||
scalefactor 2048 times the quant range of 8 we can encode residuals up to 2**14.
|
||||
|
||||
The scalefactor values are computed as:
|
||||
scalefactor_tab[s] <- round(pow(s + 1, 2.75)) */
|
||||
|
||||
static const int qoa_scalefactor_tab[16] = {
|
||||
1, 7, 21, 45, 84, 138, 211, 304, 421, 562, 731, 928, 1157, 1419, 1715, 2048
|
||||
};
|
||||
|
||||
|
||||
/* The reciprocal_tab maps each of the 16 scalefactors to their rounded
|
||||
reciprocals 1/scalefactor. This allows us to calculate the scaled residuals in
|
||||
the encoder with just one multiplication instead of an expensive division. We
|
||||
do this in .16 fixed point with integers, instead of floats.
|
||||
|
||||
The reciprocal_tab is computed as:
|
||||
reciprocal_tab[s] <- ((1<<16) + scalefactor_tab[s] - 1) / scalefactor_tab[s] */
|
||||
|
||||
static const int qoa_reciprocal_tab[16] = {
|
||||
65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32
|
||||
};
|
||||
|
||||
|
||||
/* The dequant_tab maps each of the scalefactors and quantized residuals to
|
||||
their unscaled & dequantized version.
|
||||
|
||||
Since qoa_div rounds away from the zero, the smallest entries are mapped to 3/4
|
||||
instead of 1. The dequant_tab assumes the following dequantized values for each
|
||||
of the quant_tab indices and is computed as:
|
||||
float dqt[8] = {0.75, -0.75, 2.5, -2.5, 4.5, -4.5, 7, -7};
|
||||
dequant_tab[s][q] <- round_ties_away_from_zero(scalefactor_tab[s] * dqt[q])
|
||||
|
||||
The rounding employed here is "to nearest, ties away from zero", i.e. positive
|
||||
and negative values are treated symmetrically.
|
||||
*/
|
||||
|
||||
static const int qoa_dequant_tab[16][8] = {
|
||||
{ 1, -1, 3, -3, 5, -5, 7, -7},
|
||||
{ 5, -5, 18, -18, 32, -32, 49, -49},
|
||||
{ 16, -16, 53, -53, 95, -95, 147, -147},
|
||||
{ 34, -34, 113, -113, 203, -203, 315, -315},
|
||||
{ 63, -63, 210, -210, 378, -378, 588, -588},
|
||||
{ 104, -104, 345, -345, 621, -621, 966, -966},
|
||||
{ 158, -158, 528, -528, 950, -950, 1477, -1477},
|
||||
{ 228, -228, 760, -760, 1368, -1368, 2128, -2128},
|
||||
{ 316, -316, 1053, -1053, 1895, -1895, 2947, -2947},
|
||||
{ 422, -422, 1405, -1405, 2529, -2529, 3934, -3934},
|
||||
{ 548, -548, 1828, -1828, 3290, -3290, 5117, -5117},
|
||||
{ 696, -696, 2320, -2320, 4176, -4176, 6496, -6496},
|
||||
{ 868, -868, 2893, -2893, 5207, -5207, 8099, -8099},
|
||||
{1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933},
|
||||
{1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005},
|
||||
{1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336},
|
||||
};
|
||||
|
||||
|
||||
/* The Least Mean Squares Filter is the heart of QOA. It predicts the next
|
||||
sample based on the previous 4 reconstructed samples. It does so by continuously
|
||||
adjusting 4 weights based on the residual of the previous prediction.
|
||||
|
||||
The next sample is predicted as the sum of (weight[i] * history[i]).
|
||||
|
||||
The adjustment of the weights is done with a "Sign-Sign-LMS" that adds or
|
||||
subtracts the residual to each weight, based on the corresponding sample from
|
||||
the history. This, surprisingly, is sufficient to get worthwhile predictions.
|
||||
|
||||
This is all done with fixed point integers. Hence the right-shifts when updating
|
||||
the weights and calculating the prediction. */
|
||||
|
||||
static int qoa_lms_predict(qoa_lms_t *lms) {
|
||||
int prediction = 0;
|
||||
for (int i = 0; i < QOA_LMS_LEN; i++) {
|
||||
prediction += lms->weights[i] * lms->history[i];
|
||||
}
|
||||
return prediction >> 13;
|
||||
}
|
||||
|
||||
static void qoa_lms_update(qoa_lms_t *lms, int sample, int residual) {
|
||||
int delta = residual >> 4;
|
||||
for (int i = 0; i < QOA_LMS_LEN; i++) {
|
||||
lms->weights[i] += lms->history[i] < 0 ? -delta : delta;
|
||||
}
|
||||
|
||||
for (int i = 0; i < QOA_LMS_LEN-1; i++) {
|
||||
lms->history[i] = lms->history[i+1];
|
||||
}
|
||||
lms->history[QOA_LMS_LEN-1] = sample;
|
||||
}
|
||||
|
||||
|
||||
/* qoa_div() implements a rounding division, but avoids rounding to zero for
|
||||
small numbers. E.g. 0.1 will be rounded to 1. Note that 0 itself still
|
||||
returns as 0, which is handled in the qoa_quant_tab[].
|
||||
qoa_div() takes an index into the .16 fixed point qoa_reciprocal_tab as an
|
||||
argument, so it can do the division with a cheaper integer multiplication. */
|
||||
|
||||
static inline int qoa_div(int v, int scalefactor) {
|
||||
int reciprocal = qoa_reciprocal_tab[scalefactor];
|
||||
int n = (v * reciprocal + (1 << 15)) >> 16;
|
||||
n = n + ((v > 0) - (v < 0)) - ((n > 0) - (n < 0)); /* round away from 0 */
|
||||
return n;
|
||||
}
|
||||
|
||||
static inline int qoa_clamp(int v, int min, int max) {
|
||||
if (v < min) { return min; }
|
||||
if (v > max) { return max; }
|
||||
return v;
|
||||
}
|
||||
|
||||
/* This specialized clamp function for the signed 16 bit range improves decode
|
||||
performance quite a bit. The extra if() statement works nicely with the CPUs
|
||||
branch prediction as this branch is rarely taken. */
|
||||
|
||||
static inline int qoa_clamp_s16(int v) {
|
||||
if ((unsigned int)(v + 32768) > 65535) {
|
||||
if (v < -32768) { return -32768; }
|
||||
if (v > 32767) { return 32767; }
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
static inline qoa_uint64_t qoa_read_u64(const unsigned char *bytes, unsigned int *p) {
|
||||
bytes += *p;
|
||||
*p += 8;
|
||||
return
|
||||
((qoa_uint64_t)(bytes[0]) << 56) | ((qoa_uint64_t)(bytes[1]) << 48) |
|
||||
((qoa_uint64_t)(bytes[2]) << 40) | ((qoa_uint64_t)(bytes[3]) << 32) |
|
||||
((qoa_uint64_t)(bytes[4]) << 24) | ((qoa_uint64_t)(bytes[5]) << 16) |
|
||||
((qoa_uint64_t)(bytes[6]) << 8) | ((qoa_uint64_t)(bytes[7]) << 0);
|
||||
}
|
||||
|
||||
static inline void qoa_write_u64(qoa_uint64_t v, unsigned char *bytes, unsigned int *p) {
|
||||
bytes += *p;
|
||||
*p += 8;
|
||||
bytes[0] = (v >> 56) & 0xff;
|
||||
bytes[1] = (v >> 48) & 0xff;
|
||||
bytes[2] = (v >> 40) & 0xff;
|
||||
bytes[3] = (v >> 32) & 0xff;
|
||||
bytes[4] = (v >> 24) & 0xff;
|
||||
bytes[5] = (v >> 16) & 0xff;
|
||||
bytes[6] = (v >> 8) & 0xff;
|
||||
bytes[7] = (v >> 0) & 0xff;
|
||||
}
|
||||
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
Encoder */
|
||||
|
||||
unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes) {
|
||||
unsigned int p = 0;
|
||||
qoa_write_u64(((qoa_uint64_t)QOA_MAGIC << 32) | qoa->samples, bytes, &p);
|
||||
return p;
|
||||
}
|
||||
|
||||
unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes) {
|
||||
unsigned int channels = qoa->channels;
|
||||
|
||||
unsigned int p = 0;
|
||||
unsigned int slices = (frame_len + QOA_SLICE_LEN - 1) / QOA_SLICE_LEN;
|
||||
unsigned int frame_size = QOA_FRAME_SIZE(channels, slices);
|
||||
int prev_scalefactor[QOA_MAX_CHANNELS] = {0};
|
||||
|
||||
/* Write the frame header */
|
||||
qoa_write_u64((
|
||||
(qoa_uint64_t)qoa->channels << 56 |
|
||||
(qoa_uint64_t)qoa->samplerate << 32 |
|
||||
(qoa_uint64_t)frame_len << 16 |
|
||||
(qoa_uint64_t)frame_size
|
||||
), bytes, &p);
|
||||
|
||||
|
||||
for (unsigned int c = 0; c < channels; c++) {
|
||||
/* Write the current LMS state */
|
||||
qoa_uint64_t weights = 0;
|
||||
qoa_uint64_t history = 0;
|
||||
for (int i = 0; i < QOA_LMS_LEN; i++) {
|
||||
history = (history << 16) | (qoa->lms[c].history[i] & 0xffff);
|
||||
weights = (weights << 16) | (qoa->lms[c].weights[i] & 0xffff);
|
||||
}
|
||||
qoa_write_u64(history, bytes, &p);
|
||||
qoa_write_u64(weights, bytes, &p);
|
||||
}
|
||||
|
||||
/* We encode all samples with the channels interleaved on a slice level.
|
||||
E.g. for stereo: (ch-0, slice 0), (ch 1, slice 0), (ch 0, slice 1), ...*/
|
||||
for (unsigned int sample_index = 0; sample_index < frame_len; sample_index += QOA_SLICE_LEN) {
|
||||
|
||||
for (unsigned int c = 0; c < channels; c++) {
|
||||
int slice_len = qoa_clamp(QOA_SLICE_LEN, 0, frame_len - sample_index);
|
||||
int slice_start = sample_index * channels + c;
|
||||
int slice_end = (sample_index + slice_len) * channels + c;
|
||||
|
||||
/* Brute for search for the best scalefactor. Just go through all
|
||||
16 scalefactors, encode all samples for the current slice and
|
||||
meassure the total squared error. */
|
||||
qoa_uint64_t best_rank = -1;
|
||||
#ifdef QOA_RECORD_TOTAL_ERROR
|
||||
qoa_uint64_t best_error = -1;
|
||||
#endif
|
||||
qoa_uint64_t best_slice = 0;
|
||||
qoa_lms_t best_lms;
|
||||
int best_scalefactor = 0;
|
||||
|
||||
for (int sfi = 0; sfi < 16; sfi++) {
|
||||
/* There is a strong correlation between the scalefactors of
|
||||
neighboring slices. As an optimization, start testing
|
||||
the best scalefactor of the previous slice first. */
|
||||
int scalefactor = (sfi + prev_scalefactor[c]) % 16;
|
||||
|
||||
/* We have to reset the LMS state to the last known good one
|
||||
before trying each scalefactor, as each pass updates the LMS
|
||||
state when encoding. */
|
||||
qoa_lms_t lms = qoa->lms[c];
|
||||
qoa_uint64_t slice = scalefactor;
|
||||
qoa_uint64_t current_rank = 0;
|
||||
#ifdef QOA_RECORD_TOTAL_ERROR
|
||||
qoa_uint64_t current_error = 0;
|
||||
#endif
|
||||
|
||||
for (int si = slice_start; si < slice_end; si += channels) {
|
||||
int sample = sample_data[si];
|
||||
int predicted = qoa_lms_predict(&lms);
|
||||
|
||||
int residual = sample - predicted;
|
||||
int scaled = qoa_div(residual, scalefactor);
|
||||
int clamped = qoa_clamp(scaled, -8, 8);
|
||||
int quantized = qoa_quant_tab[clamped + 8];
|
||||
int dequantized = qoa_dequant_tab[scalefactor][quantized];
|
||||
int reconstructed = qoa_clamp_s16(predicted + dequantized);
|
||||
|
||||
|
||||
/* If the weights have grown too large, we introduce a penalty
|
||||
here. This prevents pops/clicks in certain problem cases */
|
||||
int weights_penalty = ((
|
||||
lms.weights[0] * lms.weights[0] +
|
||||
lms.weights[1] * lms.weights[1] +
|
||||
lms.weights[2] * lms.weights[2] +
|
||||
lms.weights[3] * lms.weights[3]
|
||||
) >> 18) - 0x8ff;
|
||||
if (weights_penalty < 0) {
|
||||
weights_penalty = 0;
|
||||
}
|
||||
|
||||
long long error = (sample - reconstructed);
|
||||
qoa_uint64_t error_sq = error * error;
|
||||
|
||||
current_rank += error_sq + weights_penalty * weights_penalty;
|
||||
#ifdef QOA_RECORD_TOTAL_ERROR
|
||||
current_error += error_sq;
|
||||
#endif
|
||||
if (current_rank > best_rank) {
|
||||
break;
|
||||
}
|
||||
|
||||
qoa_lms_update(&lms, reconstructed, dequantized);
|
||||
slice = (slice << 3) | quantized;
|
||||
}
|
||||
|
||||
if (current_rank < best_rank) {
|
||||
best_rank = current_rank;
|
||||
#ifdef QOA_RECORD_TOTAL_ERROR
|
||||
best_error = current_error;
|
||||
#endif
|
||||
best_slice = slice;
|
||||
best_lms = lms;
|
||||
best_scalefactor = scalefactor;
|
||||
}
|
||||
}
|
||||
|
||||
prev_scalefactor[c] = best_scalefactor;
|
||||
|
||||
qoa->lms[c] = best_lms;
|
||||
#ifdef QOA_RECORD_TOTAL_ERROR
|
||||
qoa->error += best_error;
|
||||
#endif
|
||||
|
||||
/* If this slice was shorter than QOA_SLICE_LEN, we have to left-
|
||||
shift all encoded data, to ensure the rightmost bits are the empty
|
||||
ones. This should only happen in the last frame of a file as all
|
||||
slices are completely filled otherwise. */
|
||||
best_slice <<= (QOA_SLICE_LEN - slice_len) * 3;
|
||||
qoa_write_u64(best_slice, bytes, &p);
|
||||
}
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len) {
|
||||
if (
|
||||
qoa->samples == 0 ||
|
||||
qoa->samplerate == 0 || qoa->samplerate > 0xffffff ||
|
||||
qoa->channels == 0 || qoa->channels > QOA_MAX_CHANNELS
|
||||
) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Calculate the encoded size and allocate */
|
||||
unsigned int num_frames = (qoa->samples + QOA_FRAME_LEN-1) / QOA_FRAME_LEN;
|
||||
unsigned int num_slices = (qoa->samples + QOA_SLICE_LEN-1) / QOA_SLICE_LEN;
|
||||
unsigned int encoded_size = 8 + /* 8 byte file header */
|
||||
num_frames * 8 + /* 8 byte frame headers */
|
||||
num_frames * QOA_LMS_LEN * 4 * qoa->channels + /* 4 * 4 bytes lms state per channel */
|
||||
num_slices * 8 * qoa->channels; /* 8 byte slices */
|
||||
|
||||
unsigned char *bytes = QOA_MALLOC(encoded_size);
|
||||
|
||||
for (unsigned int c = 0; c < qoa->channels; c++) {
|
||||
/* Set the initial LMS weights to {0, 0, -1, 2}. This helps with the
|
||||
prediction of the first few ms of a file. */
|
||||
qoa->lms[c].weights[0] = 0;
|
||||
qoa->lms[c].weights[1] = 0;
|
||||
qoa->lms[c].weights[2] = -(1<<13);
|
||||
qoa->lms[c].weights[3] = (1<<14);
|
||||
|
||||
/* Explicitly set the history samples to 0, as we might have some
|
||||
garbage in there. */
|
||||
for (int i = 0; i < QOA_LMS_LEN; i++) {
|
||||
qoa->lms[c].history[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Encode the header and go through all frames */
|
||||
unsigned int p = qoa_encode_header(qoa, bytes);
|
||||
#ifdef QOA_RECORD_TOTAL_ERROR
|
||||
qoa->error = 0;
|
||||
#endif
|
||||
|
||||
int frame_len = QOA_FRAME_LEN;
|
||||
for (unsigned int sample_index = 0; sample_index < qoa->samples; sample_index += frame_len) {
|
||||
frame_len = qoa_clamp(QOA_FRAME_LEN, 0, qoa->samples - sample_index);
|
||||
const short *frame_samples = sample_data + sample_index * qoa->channels;
|
||||
unsigned int frame_size = qoa_encode_frame(frame_samples, qoa, frame_len, bytes + p);
|
||||
p += frame_size;
|
||||
}
|
||||
|
||||
*out_len = p;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
Decoder */
|
||||
|
||||
unsigned int qoa_max_frame_size(qoa_desc *qoa) {
|
||||
return QOA_FRAME_SIZE(qoa->channels, QOA_SLICES_PER_FRAME);
|
||||
}
|
||||
|
||||
unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa) {
|
||||
unsigned int p = 0;
|
||||
if (size < QOA_MIN_FILESIZE) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/* Read the file header, verify the magic number ('qoaf') and read the
|
||||
total number of samples. */
|
||||
qoa_uint64_t file_header = qoa_read_u64(bytes, &p);
|
||||
|
||||
if ((file_header >> 32) != QOA_MAGIC) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
qoa->samples = file_header & 0xffffffff;
|
||||
if (!qoa->samples) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Peek into the first frame header to get the number of channels and
|
||||
the samplerate. */
|
||||
qoa_uint64_t frame_header = qoa_read_u64(bytes, &p);
|
||||
qoa->channels = (frame_header >> 56) & 0x0000ff;
|
||||
qoa->samplerate = (frame_header >> 32) & 0xffffff;
|
||||
|
||||
if (qoa->channels == 0 || qoa->samples == 0 || qoa->samplerate == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 8;
|
||||
}
|
||||
|
||||
unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len) {
|
||||
unsigned int p = 0;
|
||||
*frame_len = 0;
|
||||
|
||||
if (size < 8 + QOA_LMS_LEN * 4 * qoa->channels) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Read and verify the frame header */
|
||||
qoa_uint64_t frame_header = qoa_read_u64(bytes, &p);
|
||||
unsigned int channels = (frame_header >> 56) & 0x0000ff;
|
||||
unsigned int samplerate = (frame_header >> 32) & 0xffffff;
|
||||
unsigned int samples = (frame_header >> 16) & 0x00ffff;
|
||||
unsigned int frame_size = (frame_header ) & 0x00ffff;
|
||||
|
||||
unsigned int data_size = frame_size - 8 - QOA_LMS_LEN * 4 * channels;
|
||||
unsigned int num_slices = data_size / 8;
|
||||
unsigned int max_total_samples = num_slices * QOA_SLICE_LEN;
|
||||
|
||||
if (
|
||||
channels != qoa->channels ||
|
||||
samplerate != qoa->samplerate ||
|
||||
frame_size > size ||
|
||||
samples * channels > max_total_samples
|
||||
) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/* Read the LMS state: 4 x 2 bytes history, 4 x 2 bytes weights per channel */
|
||||
for (unsigned int c = 0; c < channels; c++) {
|
||||
qoa_uint64_t history = qoa_read_u64(bytes, &p);
|
||||
qoa_uint64_t weights = qoa_read_u64(bytes, &p);
|
||||
for (int i = 0; i < QOA_LMS_LEN; i++) {
|
||||
qoa->lms[c].history[i] = ((signed short)(history >> 48));
|
||||
history <<= 16;
|
||||
qoa->lms[c].weights[i] = ((signed short)(weights >> 48));
|
||||
weights <<= 16;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Decode all slices for all channels in this frame */
|
||||
for (unsigned int sample_index = 0; sample_index < samples; sample_index += QOA_SLICE_LEN) {
|
||||
for (unsigned int c = 0; c < channels; c++) {
|
||||
qoa_uint64_t slice = qoa_read_u64(bytes, &p);
|
||||
|
||||
int scalefactor = (slice >> 60) & 0xf;
|
||||
slice <<= 4;
|
||||
|
||||
int slice_start = sample_index * channels + c;
|
||||
int slice_end = qoa_clamp(sample_index + QOA_SLICE_LEN, 0, samples) * channels + c;
|
||||
|
||||
for (int si = slice_start; si < slice_end; si += channels) {
|
||||
int predicted = qoa_lms_predict(&qoa->lms[c]);
|
||||
int quantized = (slice >> 61) & 0x7;
|
||||
int dequantized = qoa_dequant_tab[scalefactor][quantized];
|
||||
int reconstructed = qoa_clamp_s16(predicted + dequantized);
|
||||
|
||||
sample_data[si] = reconstructed;
|
||||
slice <<= 3;
|
||||
|
||||
qoa_lms_update(&qoa->lms[c], reconstructed, dequantized);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*frame_len = samples;
|
||||
return p;
|
||||
}
|
||||
|
||||
short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *qoa) {
|
||||
unsigned int p = qoa_decode_header(bytes, size, qoa);
|
||||
if (!p) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Calculate the required size of the sample buffer and allocate */
|
||||
int total_samples = qoa->samples * qoa->channels;
|
||||
short *sample_data = QOA_MALLOC(total_samples * sizeof(short));
|
||||
|
||||
unsigned int sample_index = 0;
|
||||
unsigned int frame_len;
|
||||
unsigned int frame_size;
|
||||
|
||||
/* Decode all frames */
|
||||
do {
|
||||
short *sample_ptr = sample_data + sample_index * qoa->channels;
|
||||
frame_size = qoa_decode_frame(bytes + p, size - p, qoa, sample_ptr, &frame_len);
|
||||
|
||||
p += frame_size;
|
||||
sample_index += frame_len;
|
||||
} while (frame_size && sample_index < qoa->samples);
|
||||
|
||||
qoa->samples = sample_index;
|
||||
return sample_data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
File read/write convenience functions */
|
||||
|
||||
#ifndef QOA_NO_STDIO
|
||||
#include <stdio.h>
|
||||
|
||||
int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa) {
|
||||
FILE *f = fopen(filename, "wb");
|
||||
unsigned int size;
|
||||
void *encoded;
|
||||
|
||||
if (!f) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
encoded = qoa_encode(sample_data, qoa, &size);
|
||||
if (!encoded) {
|
||||
fclose(f);
|
||||
return 0;
|
||||
}
|
||||
|
||||
fwrite(encoded, 1, size, f);
|
||||
fclose(f);
|
||||
|
||||
QOA_FREE(encoded);
|
||||
return size;
|
||||
}
|
||||
|
||||
void *qoa_read(const char *filename, qoa_desc *qoa) {
|
||||
FILE *f = fopen(filename, "rb");
|
||||
int size, bytes_read;
|
||||
void *data;
|
||||
short *sample_data;
|
||||
|
||||
if (!f) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
fseek(f, 0, SEEK_END);
|
||||
size = ftell(f);
|
||||
if (size <= 0) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
fseek(f, 0, SEEK_SET);
|
||||
|
||||
data = QOA_MALLOC(size);
|
||||
if (!data) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bytes_read = fread(data, 1, size, f);
|
||||
fclose(f);
|
||||
|
||||
sample_data = qoa_decode(data, bytes_read, qoa);
|
||||
QOA_FREE(data);
|
||||
return sample_data;
|
||||
}
|
||||
|
||||
#endif /* QOA_NO_STDIO */
|
||||
#endif /* QOA_IMPLEMENTATION */
|
||||
649
source/qoi.h
649
source/qoi.h
@@ -1,649 +0,0 @@
|
||||
/*
|
||||
|
||||
Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org
|
||||
SPDX-License-Identifier: MIT
|
||||
|
||||
|
||||
QOI - The "Quite OK Image" format for fast, lossless image compression
|
||||
|
||||
-- About
|
||||
|
||||
QOI encodes and decodes images in a lossless format. Compared to stb_image and
|
||||
stb_image_write QOI offers 20x-50x faster encoding, 3x-4x faster decoding and
|
||||
20% better compression.
|
||||
|
||||
|
||||
-- Synopsis
|
||||
|
||||
// Define `QOI_IMPLEMENTATION` in *one* C/C++ file before including this
|
||||
// library to create the implementation.
|
||||
|
||||
#define QOI_IMPLEMENTATION
|
||||
#include "qoi.h"
|
||||
|
||||
// Encode and store an RGBA buffer to the file system. The qoi_desc describes
|
||||
// the input pixel data.
|
||||
qoi_write("image_new.qoi", rgba_pixels, &(qoi_desc){
|
||||
.width = 1920,
|
||||
.height = 1080,
|
||||
.channels = 4,
|
||||
.colorspace = QOI_SRGB
|
||||
});
|
||||
|
||||
// Load and decode a QOI image from the file system into a 32bbp RGBA buffer.
|
||||
// The qoi_desc struct will be filled with the width, height, number of channels
|
||||
// and colorspace read from the file header.
|
||||
qoi_desc desc;
|
||||
void *rgba_pixels = qoi_read("image.qoi", &desc, 4);
|
||||
|
||||
|
||||
|
||||
-- Documentation
|
||||
|
||||
This library provides the following functions;
|
||||
- qoi_read -- read and decode a QOI file
|
||||
- qoi_decode -- decode the raw bytes of a QOI image from memory
|
||||
- qoi_write -- encode and write a QOI file
|
||||
- qoi_encode -- encode an rgba buffer into a QOI image in memory
|
||||
|
||||
See the function declaration below for the signature and more information.
|
||||
|
||||
If you don't want/need the qoi_read and qoi_write functions, you can define
|
||||
QOI_NO_STDIO before including this library.
|
||||
|
||||
This library uses malloc() and free(). To supply your own malloc implementation
|
||||
you can define QOI_MALLOC and QOI_FREE before including this library.
|
||||
|
||||
This library uses memset() to zero-initialize the index. To supply your own
|
||||
implementation you can define QOI_ZEROARR before including this library.
|
||||
|
||||
|
||||
-- Data Format
|
||||
|
||||
A QOI file has a 14 byte header, followed by any number of data "chunks" and an
|
||||
8-byte end marker.
|
||||
|
||||
struct qoi_header_t {
|
||||
char magic[4]; // magic bytes "qoif"
|
||||
uint32_t width; // image width in pixels (BE)
|
||||
uint32_t height; // image height in pixels (BE)
|
||||
uint8_t channels; // 3 = RGB, 4 = RGBA
|
||||
uint8_t colorspace; // 0 = sRGB with linear alpha, 1 = all channels linear
|
||||
};
|
||||
|
||||
Images are encoded row by row, left to right, top to bottom. The decoder and
|
||||
encoder start with {r: 0, g: 0, b: 0, a: 255} as the previous pixel value. An
|
||||
image is complete when all pixels specified by width * height have been covered.
|
||||
|
||||
Pixels are encoded as
|
||||
- a run of the previous pixel
|
||||
- an index into an array of previously seen pixels
|
||||
- a difference to the previous pixel value in r,g,b
|
||||
- full r,g,b or r,g,b,a values
|
||||
|
||||
The color channels are assumed to not be premultiplied with the alpha channel
|
||||
("un-premultiplied alpha").
|
||||
|
||||
A running array[64] (zero-initialized) of previously seen pixel values is
|
||||
maintained by the encoder and decoder. Each pixel that is seen by the encoder
|
||||
and decoder is put into this array at the position formed by a hash function of
|
||||
the color value. In the encoder, if the pixel value at the index matches the
|
||||
current pixel, this index position is written to the stream as QOI_OP_INDEX.
|
||||
The hash function for the index is:
|
||||
|
||||
index_position = (r * 3 + g * 5 + b * 7 + a * 11) % 64
|
||||
|
||||
Each chunk starts with a 2- or 8-bit tag, followed by a number of data bits. The
|
||||
bit length of chunks is divisible by 8 - i.e. all chunks are byte aligned. All
|
||||
values encoded in these data bits have the most significant bit on the left.
|
||||
|
||||
The 8-bit tags have precedence over the 2-bit tags. A decoder must check for the
|
||||
presence of an 8-bit tag first.
|
||||
|
||||
The byte stream's end is marked with 7 0x00 bytes followed a single 0x01 byte.
|
||||
|
||||
|
||||
The possible chunks are:
|
||||
|
||||
|
||||
.- QOI_OP_INDEX ----------.
|
||||
| Byte[0] |
|
||||
| 7 6 5 4 3 2 1 0 |
|
||||
|-------+-----------------|
|
||||
| 0 0 | index |
|
||||
`-------------------------`
|
||||
2-bit tag b00
|
||||
6-bit index into the color index array: 0..63
|
||||
|
||||
A valid encoder must not issue 2 or more consecutive QOI_OP_INDEX chunks to the
|
||||
same index. QOI_OP_RUN should be used instead.
|
||||
|
||||
|
||||
.- QOI_OP_DIFF -----------.
|
||||
| Byte[0] |
|
||||
| 7 6 5 4 3 2 1 0 |
|
||||
|-------+-----+-----+-----|
|
||||
| 0 1 | dr | dg | db |
|
||||
`-------------------------`
|
||||
2-bit tag b01
|
||||
2-bit red channel difference from the previous pixel between -2..1
|
||||
2-bit green channel difference from the previous pixel between -2..1
|
||||
2-bit blue channel difference from the previous pixel between -2..1
|
||||
|
||||
The difference to the current channel values are using a wraparound operation,
|
||||
so "1 - 2" will result in 255, while "255 + 1" will result in 0.
|
||||
|
||||
Values are stored as unsigned integers with a bias of 2. E.g. -2 is stored as
|
||||
0 (b00). 1 is stored as 3 (b11).
|
||||
|
||||
The alpha value remains unchanged from the previous pixel.
|
||||
|
||||
|
||||
.- QOI_OP_LUMA -------------------------------------.
|
||||
| Byte[0] | Byte[1] |
|
||||
| 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 |
|
||||
|-------+-----------------+-------------+-----------|
|
||||
| 1 0 | green diff | dr - dg | db - dg |
|
||||
`---------------------------------------------------`
|
||||
2-bit tag b10
|
||||
6-bit green channel difference from the previous pixel -32..31
|
||||
4-bit red channel difference minus green channel difference -8..7
|
||||
4-bit blue channel difference minus green channel difference -8..7
|
||||
|
||||
The green channel is used to indicate the general direction of change and is
|
||||
encoded in 6 bits. The red and blue channels (dr and db) base their diffs off
|
||||
of the green channel difference and are encoded in 4 bits. I.e.:
|
||||
dr_dg = (cur_px.r - prev_px.r) - (cur_px.g - prev_px.g)
|
||||
db_dg = (cur_px.b - prev_px.b) - (cur_px.g - prev_px.g)
|
||||
|
||||
The difference to the current channel values are using a wraparound operation,
|
||||
so "10 - 13" will result in 253, while "250 + 7" will result in 1.
|
||||
|
||||
Values are stored as unsigned integers with a bias of 32 for the green channel
|
||||
and a bias of 8 for the red and blue channel.
|
||||
|
||||
The alpha value remains unchanged from the previous pixel.
|
||||
|
||||
|
||||
.- QOI_OP_RUN ------------.
|
||||
| Byte[0] |
|
||||
| 7 6 5 4 3 2 1 0 |
|
||||
|-------+-----------------|
|
||||
| 1 1 | run |
|
||||
`-------------------------`
|
||||
2-bit tag b11
|
||||
6-bit run-length repeating the previous pixel: 1..62
|
||||
|
||||
The run-length is stored with a bias of -1. Note that the run-lengths 63 and 64
|
||||
(b111110 and b111111) are illegal as they are occupied by the QOI_OP_RGB and
|
||||
QOI_OP_RGBA tags.
|
||||
|
||||
|
||||
.- QOI_OP_RGB ------------------------------------------.
|
||||
| Byte[0] | Byte[1] | Byte[2] | Byte[3] |
|
||||
| 7 6 5 4 3 2 1 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 |
|
||||
|-------------------------+---------+---------+---------|
|
||||
| 1 1 1 1 1 1 1 0 | red | green | blue |
|
||||
`-------------------------------------------------------`
|
||||
8-bit tag b11111110
|
||||
8-bit red channel value
|
||||
8-bit green channel value
|
||||
8-bit blue channel value
|
||||
|
||||
The alpha value remains unchanged from the previous pixel.
|
||||
|
||||
|
||||
.- QOI_OP_RGBA ---------------------------------------------------.
|
||||
| Byte[0] | Byte[1] | Byte[2] | Byte[3] | Byte[4] |
|
||||
| 7 6 5 4 3 2 1 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 |
|
||||
|-------------------------+---------+---------+---------+---------|
|
||||
| 1 1 1 1 1 1 1 1 | red | green | blue | alpha |
|
||||
`-----------------------------------------------------------------`
|
||||
8-bit tag b11111111
|
||||
8-bit red channel value
|
||||
8-bit green channel value
|
||||
8-bit blue channel value
|
||||
8-bit alpha channel value
|
||||
|
||||
*/
|
||||
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
Header - Public functions */
|
||||
|
||||
#ifndef QOI_H
|
||||
#define QOI_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* A pointer to a qoi_desc struct has to be supplied to all of qoi's functions.
|
||||
It describes either the input format (for qoi_write and qoi_encode), or is
|
||||
filled with the description read from the file header (for qoi_read and
|
||||
qoi_decode).
|
||||
|
||||
The colorspace in this qoi_desc is an enum where
|
||||
0 = sRGB, i.e. gamma scaled RGB channels and a linear alpha channel
|
||||
1 = all channels are linear
|
||||
You may use the constants QOI_SRGB or QOI_LINEAR. The colorspace is purely
|
||||
informative. It will be saved to the file header, but does not affect
|
||||
how chunks are en-/decoded. */
|
||||
|
||||
#define QOI_SRGB 0
|
||||
#define QOI_LINEAR 1
|
||||
|
||||
typedef struct {
|
||||
unsigned int width;
|
||||
unsigned int height;
|
||||
unsigned char channels;
|
||||
unsigned char colorspace;
|
||||
} qoi_desc;
|
||||
|
||||
#ifndef QOI_NO_STDIO
|
||||
|
||||
/* Encode raw RGB or RGBA pixels into a QOI image and write it to the file
|
||||
system. The qoi_desc struct must be filled with the image width, height,
|
||||
number of channels (3 = RGB, 4 = RGBA) and the colorspace.
|
||||
|
||||
The function returns 0 on failure (invalid parameters, or fopen or malloc
|
||||
failed) or the number of bytes written on success. */
|
||||
|
||||
int qoi_write(const char *filename, const void *data, const qoi_desc *desc);
|
||||
|
||||
|
||||
/* Read and decode a QOI image from the file system. If channels is 0, the
|
||||
number of channels from the file header is used. If channels is 3 or 4 the
|
||||
output format will be forced into this number of channels.
|
||||
|
||||
The function either returns NULL on failure (invalid data, or malloc or fopen
|
||||
failed) or a pointer to the decoded pixels. On success, the qoi_desc struct
|
||||
will be filled with the description from the file header.
|
||||
|
||||
The returned pixel data should be free()d after use. */
|
||||
|
||||
void *qoi_read(const char *filename, qoi_desc *desc, int channels);
|
||||
|
||||
#endif /* QOI_NO_STDIO */
|
||||
|
||||
|
||||
/* Encode raw RGB or RGBA pixels into a QOI image in memory.
|
||||
|
||||
The function either returns NULL on failure (invalid parameters or malloc
|
||||
failed) or a pointer to the encoded data on success. On success the out_len
|
||||
is set to the size in bytes of the encoded data.
|
||||
|
||||
The returned qoi data should be free()d after use. */
|
||||
|
||||
void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len);
|
||||
|
||||
|
||||
/* Decode a QOI image from memory.
|
||||
|
||||
The function either returns NULL on failure (invalid parameters or malloc
|
||||
failed) or a pointer to the decoded pixels. On success, the qoi_desc struct
|
||||
is filled with the description from the file header.
|
||||
|
||||
The returned pixel data should be free()d after use. */
|
||||
|
||||
void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif /* QOI_H */
|
||||
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
Implementation */
|
||||
|
||||
#ifdef QOI_IMPLEMENTATION
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef QOI_MALLOC
|
||||
#define QOI_MALLOC(sz) malloc(sz)
|
||||
#define QOI_FREE(p) free(p)
|
||||
#endif
|
||||
#ifndef QOI_ZEROARR
|
||||
#define QOI_ZEROARR(a) memset((a),0,sizeof(a))
|
||||
#endif
|
||||
|
||||
#define QOI_OP_INDEX 0x00 /* 00xxxxxx */
|
||||
#define QOI_OP_DIFF 0x40 /* 01xxxxxx */
|
||||
#define QOI_OP_LUMA 0x80 /* 10xxxxxx */
|
||||
#define QOI_OP_RUN 0xc0 /* 11xxxxxx */
|
||||
#define QOI_OP_RGB 0xfe /* 11111110 */
|
||||
#define QOI_OP_RGBA 0xff /* 11111111 */
|
||||
|
||||
#define QOI_MASK_2 0xc0 /* 11000000 */
|
||||
|
||||
#define QOI_COLOR_HASH(C) (C.rgba.r*3 + C.rgba.g*5 + C.rgba.b*7 + C.rgba.a*11)
|
||||
#define QOI_MAGIC \
|
||||
(((unsigned int)'q') << 24 | ((unsigned int)'o') << 16 | \
|
||||
((unsigned int)'i') << 8 | ((unsigned int)'f'))
|
||||
#define QOI_HEADER_SIZE 14
|
||||
|
||||
/* 2GB is the max file size that this implementation can safely handle. We guard
|
||||
against anything larger than that, assuming the worst case with 5 bytes per
|
||||
pixel, rounded down to a nice clean value. 400 million pixels ought to be
|
||||
enough for anybody. */
|
||||
#define QOI_PIXELS_MAX ((unsigned int)400000000)
|
||||
|
||||
typedef union {
|
||||
struct { unsigned char r, g, b, a; } rgba;
|
||||
unsigned int v;
|
||||
} qoi_rgba_t;
|
||||
|
||||
static const unsigned char qoi_padding[8] = {0,0,0,0,0,0,0,1};
|
||||
|
||||
static void qoi_write_32(unsigned char *bytes, int *p, unsigned int v) {
|
||||
bytes[(*p)++] = (0xff000000 & v) >> 24;
|
||||
bytes[(*p)++] = (0x00ff0000 & v) >> 16;
|
||||
bytes[(*p)++] = (0x0000ff00 & v) >> 8;
|
||||
bytes[(*p)++] = (0x000000ff & v);
|
||||
}
|
||||
|
||||
static unsigned int qoi_read_32(const unsigned char *bytes, int *p) {
|
||||
unsigned int a = bytes[(*p)++];
|
||||
unsigned int b = bytes[(*p)++];
|
||||
unsigned int c = bytes[(*p)++];
|
||||
unsigned int d = bytes[(*p)++];
|
||||
return a << 24 | b << 16 | c << 8 | d;
|
||||
}
|
||||
|
||||
void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) {
|
||||
int i, max_size, p, run;
|
||||
int px_len, px_end, px_pos, channels;
|
||||
unsigned char *bytes;
|
||||
const unsigned char *pixels;
|
||||
qoi_rgba_t index[64];
|
||||
qoi_rgba_t px, px_prev;
|
||||
|
||||
if (
|
||||
data == NULL || out_len == NULL || desc == NULL ||
|
||||
desc->width == 0 || desc->height == 0 ||
|
||||
desc->channels < 3 || desc->channels > 4 ||
|
||||
desc->colorspace > 1 ||
|
||||
desc->height >= QOI_PIXELS_MAX / desc->width
|
||||
) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
max_size =
|
||||
desc->width * desc->height * (desc->channels + 1) +
|
||||
QOI_HEADER_SIZE + sizeof(qoi_padding);
|
||||
|
||||
p = 0;
|
||||
bytes = (unsigned char *) QOI_MALLOC(max_size);
|
||||
if (!bytes) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
qoi_write_32(bytes, &p, QOI_MAGIC);
|
||||
qoi_write_32(bytes, &p, desc->width);
|
||||
qoi_write_32(bytes, &p, desc->height);
|
||||
bytes[p++] = desc->channels;
|
||||
bytes[p++] = desc->colorspace;
|
||||
|
||||
|
||||
pixels = (const unsigned char *)data;
|
||||
|
||||
QOI_ZEROARR(index);
|
||||
|
||||
run = 0;
|
||||
px_prev.rgba.r = 0;
|
||||
px_prev.rgba.g = 0;
|
||||
px_prev.rgba.b = 0;
|
||||
px_prev.rgba.a = 255;
|
||||
px = px_prev;
|
||||
|
||||
px_len = desc->width * desc->height * desc->channels;
|
||||
px_end = px_len - desc->channels;
|
||||
channels = desc->channels;
|
||||
|
||||
for (px_pos = 0; px_pos < px_len; px_pos += channels) {
|
||||
px.rgba.r = pixels[px_pos + 0];
|
||||
px.rgba.g = pixels[px_pos + 1];
|
||||
px.rgba.b = pixels[px_pos + 2];
|
||||
|
||||
if (channels == 4) {
|
||||
px.rgba.a = pixels[px_pos + 3];
|
||||
}
|
||||
|
||||
if (px.v == px_prev.v) {
|
||||
run++;
|
||||
if (run == 62 || px_pos == px_end) {
|
||||
bytes[p++] = QOI_OP_RUN | (run - 1);
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
else {
|
||||
int index_pos;
|
||||
|
||||
if (run > 0) {
|
||||
bytes[p++] = QOI_OP_RUN | (run - 1);
|
||||
run = 0;
|
||||
}
|
||||
|
||||
index_pos = QOI_COLOR_HASH(px) & (64 - 1);
|
||||
|
||||
if (index[index_pos].v == px.v) {
|
||||
bytes[p++] = QOI_OP_INDEX | index_pos;
|
||||
}
|
||||
else {
|
||||
index[index_pos] = px;
|
||||
|
||||
if (px.rgba.a == px_prev.rgba.a) {
|
||||
signed char vr = px.rgba.r - px_prev.rgba.r;
|
||||
signed char vg = px.rgba.g - px_prev.rgba.g;
|
||||
signed char vb = px.rgba.b - px_prev.rgba.b;
|
||||
|
||||
signed char vg_r = vr - vg;
|
||||
signed char vg_b = vb - vg;
|
||||
|
||||
if (
|
||||
vr > -3 && vr < 2 &&
|
||||
vg > -3 && vg < 2 &&
|
||||
vb > -3 && vb < 2
|
||||
) {
|
||||
bytes[p++] = QOI_OP_DIFF | (vr + 2) << 4 | (vg + 2) << 2 | (vb + 2);
|
||||
}
|
||||
else if (
|
||||
vg_r > -9 && vg_r < 8 &&
|
||||
vg > -33 && vg < 32 &&
|
||||
vg_b > -9 && vg_b < 8
|
||||
) {
|
||||
bytes[p++] = QOI_OP_LUMA | (vg + 32);
|
||||
bytes[p++] = (vg_r + 8) << 4 | (vg_b + 8);
|
||||
}
|
||||
else {
|
||||
bytes[p++] = QOI_OP_RGB;
|
||||
bytes[p++] = px.rgba.r;
|
||||
bytes[p++] = px.rgba.g;
|
||||
bytes[p++] = px.rgba.b;
|
||||
}
|
||||
}
|
||||
else {
|
||||
bytes[p++] = QOI_OP_RGBA;
|
||||
bytes[p++] = px.rgba.r;
|
||||
bytes[p++] = px.rgba.g;
|
||||
bytes[p++] = px.rgba.b;
|
||||
bytes[p++] = px.rgba.a;
|
||||
}
|
||||
}
|
||||
}
|
||||
px_prev = px;
|
||||
}
|
||||
|
||||
for (i = 0; i < (int)sizeof(qoi_padding); i++) {
|
||||
bytes[p++] = qoi_padding[i];
|
||||
}
|
||||
|
||||
*out_len = p;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels) {
|
||||
const unsigned char *bytes;
|
||||
unsigned int header_magic;
|
||||
unsigned char *pixels;
|
||||
qoi_rgba_t index[64];
|
||||
qoi_rgba_t px;
|
||||
int px_len, chunks_len, px_pos;
|
||||
int p = 0, run = 0;
|
||||
|
||||
if (
|
||||
data == NULL || desc == NULL ||
|
||||
(channels != 0 && channels != 3 && channels != 4) ||
|
||||
size < QOI_HEADER_SIZE + (int)sizeof(qoi_padding)
|
||||
) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bytes = (const unsigned char *)data;
|
||||
|
||||
header_magic = qoi_read_32(bytes, &p);
|
||||
desc->width = qoi_read_32(bytes, &p);
|
||||
desc->height = qoi_read_32(bytes, &p);
|
||||
desc->channels = bytes[p++];
|
||||
desc->colorspace = bytes[p++];
|
||||
|
||||
if (
|
||||
desc->width == 0 || desc->height == 0 ||
|
||||
desc->channels < 3 || desc->channels > 4 ||
|
||||
desc->colorspace > 1 ||
|
||||
header_magic != QOI_MAGIC ||
|
||||
desc->height >= QOI_PIXELS_MAX / desc->width
|
||||
) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (channels == 0) {
|
||||
channels = desc->channels;
|
||||
}
|
||||
|
||||
px_len = desc->width * desc->height * channels;
|
||||
pixels = (unsigned char *) QOI_MALLOC(px_len);
|
||||
if (!pixels) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
QOI_ZEROARR(index);
|
||||
px.rgba.r = 0;
|
||||
px.rgba.g = 0;
|
||||
px.rgba.b = 0;
|
||||
px.rgba.a = 255;
|
||||
|
||||
chunks_len = size - (int)sizeof(qoi_padding);
|
||||
for (px_pos = 0; px_pos < px_len; px_pos += channels) {
|
||||
if (run > 0) {
|
||||
run--;
|
||||
}
|
||||
else if (p < chunks_len) {
|
||||
int b1 = bytes[p++];
|
||||
|
||||
if (b1 == QOI_OP_RGB) {
|
||||
px.rgba.r = bytes[p++];
|
||||
px.rgba.g = bytes[p++];
|
||||
px.rgba.b = bytes[p++];
|
||||
}
|
||||
else if (b1 == QOI_OP_RGBA) {
|
||||
px.rgba.r = bytes[p++];
|
||||
px.rgba.g = bytes[p++];
|
||||
px.rgba.b = bytes[p++];
|
||||
px.rgba.a = bytes[p++];
|
||||
}
|
||||
else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX) {
|
||||
px = index[b1];
|
||||
}
|
||||
else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF) {
|
||||
px.rgba.r += ((b1 >> 4) & 0x03) - 2;
|
||||
px.rgba.g += ((b1 >> 2) & 0x03) - 2;
|
||||
px.rgba.b += ( b1 & 0x03) - 2;
|
||||
}
|
||||
else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA) {
|
||||
int b2 = bytes[p++];
|
||||
int vg = (b1 & 0x3f) - 32;
|
||||
px.rgba.r += vg - 8 + ((b2 >> 4) & 0x0f);
|
||||
px.rgba.g += vg;
|
||||
px.rgba.b += vg - 8 + (b2 & 0x0f);
|
||||
}
|
||||
else if ((b1 & QOI_MASK_2) == QOI_OP_RUN) {
|
||||
run = (b1 & 0x3f);
|
||||
}
|
||||
|
||||
index[QOI_COLOR_HASH(px) & (64 - 1)] = px;
|
||||
}
|
||||
|
||||
pixels[px_pos + 0] = px.rgba.r;
|
||||
pixels[px_pos + 1] = px.rgba.g;
|
||||
pixels[px_pos + 2] = px.rgba.b;
|
||||
|
||||
if (channels == 4) {
|
||||
pixels[px_pos + 3] = px.rgba.a;
|
||||
}
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
#ifndef QOI_NO_STDIO
|
||||
#include <stdio.h>
|
||||
|
||||
int qoi_write(const char *filename, const void *data, const qoi_desc *desc) {
|
||||
FILE *f = fopen(filename, "wb");
|
||||
int size, err;
|
||||
void *encoded;
|
||||
|
||||
if (!f) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
encoded = qoi_encode(data, desc, &size);
|
||||
if (!encoded) {
|
||||
fclose(f);
|
||||
return 0;
|
||||
}
|
||||
|
||||
fwrite(encoded, 1, size, f);
|
||||
fflush(f);
|
||||
err = ferror(f);
|
||||
fclose(f);
|
||||
|
||||
QOI_FREE(encoded);
|
||||
return err ? 0 : size;
|
||||
}
|
||||
|
||||
void *qoi_read(const char *filename, qoi_desc *desc, int channels) {
|
||||
FILE *f = fopen(filename, "rb");
|
||||
int size, bytes_read;
|
||||
void *pixels, *data;
|
||||
|
||||
if (!f) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
fseek(f, 0, SEEK_END);
|
||||
size = ftell(f);
|
||||
if (size <= 0 || fseek(f, 0, SEEK_SET) != 0) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
data = QOI_MALLOC(size);
|
||||
if (!data) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bytes_read = fread(data, 1, size, f);
|
||||
fclose(f);
|
||||
pixels = (bytes_read != size) ? NULL : qoi_decode(data, bytes_read, desc, channels);
|
||||
QOI_FREE(data);
|
||||
return pixels;
|
||||
}
|
||||
|
||||
#endif /* QOI_NO_STDIO */
|
||||
#endif /* QOI_IMPLEMENTATION */
|
||||
@@ -1,12 +0,0 @@
|
||||
#include "render.h"
|
||||
|
||||
viewstate globalview = {0};
|
||||
|
||||
float *rgba2floats(float *r, struct rgba c)
|
||||
{
|
||||
r[0] = (float)c.r / RGBA_MAX;
|
||||
r[1] = (float)c.g / RGBA_MAX;
|
||||
r[2] = (float)c.b / RGBA_MAX;
|
||||
r[3] = (float)c.a / RGBA_MAX;
|
||||
return r;
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
#ifndef OPENGL_RENDER_H
|
||||
#define OPENGL_RENDER_H
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#define RGBA_MAX 255
|
||||
|
||||
extern struct rgba color_white;
|
||||
extern struct rgba color_black;
|
||||
extern struct rgba color_clear;
|
||||
extern int TOPLEFT;
|
||||
|
||||
typedef struct viewstate {
|
||||
HMM_Mat4 v;
|
||||
HMM_Mat4 p;
|
||||
HMM_Mat4 vp;
|
||||
} viewstate;
|
||||
|
||||
extern viewstate globalview;
|
||||
|
||||
void capture_screen(int x, int y, int w, int h, const char *path);
|
||||
|
||||
void gif_rec_start(int w, int h, int cpf, int bitdepth);
|
||||
void gif_rec_end(const char *path);
|
||||
|
||||
struct uv_n {
|
||||
unsigned short u;
|
||||
unsigned short v;
|
||||
};
|
||||
|
||||
struct st_n {
|
||||
struct uv_n s;
|
||||
struct uv_n t;
|
||||
};
|
||||
|
||||
struct rgba {
|
||||
unsigned char r;
|
||||
unsigned char g;
|
||||
unsigned char b;
|
||||
unsigned char a;
|
||||
};
|
||||
|
||||
typedef struct rgba rgba;
|
||||
typedef HMM_Vec4 rgbaf;
|
||||
typedef HMM_Vec4 colorf;
|
||||
|
||||
// rectangles are always defined with [x,y] in the bottom left
|
||||
typedef SDL_FRect rect;
|
||||
typedef SDL_Rect irect;
|
||||
|
||||
float *rgba2floats(float *r, struct rgba c);
|
||||
|
||||
static inline float lerp(float f, float a, float b)
|
||||
{
|
||||
return a * (1.0-f)+(b*f);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,149 +0,0 @@
|
||||
#include "glad.h"
|
||||
#include <tracy/Tracy.hpp>
|
||||
#include <tracy/TracyOpenGL.hpp>
|
||||
|
||||
void trace_apply_uniforms(sg_shader_stage stage, int ub_index, const sg_range *data, void *user_data)
|
||||
{
|
||||
}
|
||||
|
||||
void trace_apply_pipeline(sg_pipeline pip, void *data)
|
||||
{
|
||||
}
|
||||
|
||||
void trace_begin_pass(const sg_pass *action, void *data)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void trace_apply_viewport(int x, int y, int width, int height, bool origin_top_left, void *user_data)
|
||||
{
|
||||
}
|
||||
|
||||
void trace_apply_bindings(const sg_bindings *bindings, void *data)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void trace_draw(int base_element, int num_elements, int num_instances, void *user_data)
|
||||
{
|
||||
}
|
||||
|
||||
void trace_alloc_buffer(sg_buffer result, void *data) {
|
||||
TracyMessageL("BUFFER ALLOC");
|
||||
}
|
||||
void trace_init_buffer(sg_buffer id, const sg_buffer_desc *desc, void *data){
|
||||
TracyMessageL("BUFFER INIT");
|
||||
}
|
||||
void trace_make_buffer(const sg_buffer_desc *desc, sg_buffer id, void *data){
|
||||
TracyAllocN((void*)id.id, desc->data.size, "buffer");
|
||||
}
|
||||
void trace_append_buffer(sg_buffer id, const sg_range *data, int result, void *user_data) {
|
||||
}
|
||||
void trace_update_buffer(sg_buffer buf, const sg_range *data, void *user_data){
|
||||
|
||||
TracyMessageL("BUFFER UPDATED");
|
||||
}
|
||||
void trace_uninit_buffer(sg_buffer id, void *data){
|
||||
TracyMessageL("BUFFER UNINIT");
|
||||
}
|
||||
void trace_dealloc_buffer(sg_buffer id, void *data){
|
||||
TracyMessageL("BUFFER DEALLOC");
|
||||
}
|
||||
void trace_destroy_buffer(sg_buffer id, void *data){
|
||||
TracyFreeN((void*)id.id, "buffer");
|
||||
}
|
||||
void trace_fail_buffer(sg_buffer id, void *data){}
|
||||
|
||||
void trace_alloc_image(sg_image result, void *data) {
|
||||
TracyMessageL("IMAGE ALLOC");
|
||||
}
|
||||
void trace_init_image(sg_image id, const sg_image_desc *desc, void *data){
|
||||
TracyMessageL("IMAGE INIT");
|
||||
}
|
||||
|
||||
int image_data_size(sg_image_data *data)
|
||||
{
|
||||
int total_size = 0;
|
||||
for (int i = 0; i < SG_CUBEFACE_NUM; i++)
|
||||
for (int j = 0; j < SG_MAX_MIPMAPS; j++)
|
||||
total_size += data->subimage[i][j].size;
|
||||
|
||||
return total_size;
|
||||
}
|
||||
|
||||
void trace_make_image(const sg_image_desc *desc, sg_image id, void *data){
|
||||
int total_size = 0;
|
||||
for (int i = 0; i < desc->num_mipmaps; i++)
|
||||
total_size += desc->data.subimage[i]->size;
|
||||
|
||||
// TracyAllocN((void*)id.id, image_data_size(&desc->data), "tex_gpu");
|
||||
}
|
||||
|
||||
void trace_update_image(sg_image id, const sg_image_data *data, void *user_data){
|
||||
// TracyFreeN((void*)id.id, "tex_gpu");
|
||||
// TracyAllocN((void*)id.id, image_data_size(data), "tex_gpu");
|
||||
}
|
||||
void trace_uninit_image(sg_image id, void *data){
|
||||
TracyMessageL("IMAGE UNINIT");
|
||||
}
|
||||
void trace_dealloc_image(sg_image id, void *data){
|
||||
TracyMessageL("IMAGE DEALLOC");
|
||||
}
|
||||
void trace_destroy_image(sg_image id, void *data){
|
||||
TracyFreeN((void*)id.id, "tex_gpu");
|
||||
}
|
||||
|
||||
void trace_fail_image(sg_image id, void *data){}
|
||||
|
||||
#define SG_HOOK_SET(NAME) \
|
||||
hooks.alloc_##NAME = trace_alloc_##NAME; \
|
||||
hooks.dealloc_##NAME = trace_dealloc_##NAME; \
|
||||
hooks.init_##NAME = trace_init_##NAME; \
|
||||
hooks.uninit_##NAME = trace_uninit_##NAME; \
|
||||
hooks.fail_##NAME = trace_fail_##NAME; \
|
||||
hooks.destroy_##NAME = trace_destroy_##NAME; \
|
||||
hooks.make_##NAME = trace_make_##NAME; \
|
||||
|
||||
static sg_trace_hooks hooks;
|
||||
|
||||
extern "C"{
|
||||
void render_trace_init()
|
||||
{
|
||||
return;
|
||||
hooks.apply_pipeline = trace_apply_pipeline;
|
||||
hooks.begin_pass = trace_begin_pass;
|
||||
SG_HOOK_SET(buffer);
|
||||
hooks.append_buffer = trace_append_buffer;
|
||||
SG_HOOK_SET(image);
|
||||
// SG_HOOK_SET(shader),
|
||||
// SG_HOOK_SET(sampler),
|
||||
// SG_HOOK_SET(pipeline),
|
||||
// SG_HOOK_SET(attachments),
|
||||
hooks.apply_uniforms = trace_apply_uniforms;
|
||||
hooks.draw = trace_draw;
|
||||
|
||||
sg_trace_hooks hh = sg_install_trace_hooks(&hooks);
|
||||
|
||||
TracyGpuContext;
|
||||
}
|
||||
}
|
||||
|
||||
/*static const JSCFunctionListEntry js_tracy_funcs[] = {
|
||||
JS_CFUNC_DEF("fiber", 1, js_tracy_fiber_enter),
|
||||
JS_CFUNC_DEF("fiber_leave", 1, js_tracy_fiber_leave),
|
||||
JS_CFUNC_DEF("gpu_zone_begin", 1, js_tracy_gpu_zone_begin),
|
||||
JS_CFUNC_DEF("gpu_zone_end", 1, js_tracy_gpu_zone_end),
|
||||
JS_CFUNC_DEF("gpu_collect", 0, js_tracy_gpu_collect),
|
||||
JS_CFUNC_DEF("end_frame", 0, js_tracy_frame_mark),
|
||||
JS_CFUNC_DEF("zone", 1, js_tracy_zone_begin),
|
||||
JS_CFUNC_DEF("message", 1, js_tracy_message),
|
||||
JS_CFUNC_DEF("plot", 2, js_tracy_plot),
|
||||
};
|
||||
|
||||
JSValue js_tracy_use(JSContext *js)
|
||||
{
|
||||
JSValue expy = JS_NewObject(js);
|
||||
JS_SetPropertyFunctionList(js, expy, js_tracy_funcs, sizeof(js_tracy_funcs)/sizeof(JSCFunctionListEntry));
|
||||
return expy;
|
||||
}
|
||||
*/
|
||||
529
source/simplex.c
529
source/simplex.c
@@ -1,529 +0,0 @@
|
||||
/*
|
||||
|
||||
C source for simplex noise generation,
|
||||
Original Java Source from: http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
|
||||
Published originally as a Garrysmod Lua Extension under the pseudonym Levybreak
|
||||
|
||||
*/
|
||||
|
||||
#include <math.h>
|
||||
#include "simplex.h"
|
||||
|
||||
double Noise(genericNoise func, int len, double inputs[])
|
||||
{
|
||||
switch (len){
|
||||
case 2:
|
||||
return func.p2(inputs[0], inputs[1]);
|
||||
case 3:
|
||||
return func.p3(inputs[0], inputs[1], inputs[2]);
|
||||
case 4:
|
||||
return func.p4(inputs[0], inputs[1], inputs[2], inputs[3]);
|
||||
default:
|
||||
return func.pn(len, inputs);
|
||||
}
|
||||
}
|
||||
|
||||
double TurbulentNoise(genericNoise func, int dir, int iter, int len, double inputs[])
|
||||
{
|
||||
double ret = fabs(Noise(func, len, inputs));
|
||||
|
||||
int i = 0;
|
||||
for (i = 0 ; i < iter ; i++){
|
||||
double num = pow(2,iter);
|
||||
double scaled[len];
|
||||
int j = 0;
|
||||
for (j = 0; j < len; j++) {
|
||||
scaled[j] = inputs[len]*(num/i);
|
||||
}
|
||||
ret = ret + (i/num)*fabs(Noise(func, len, scaled));
|
||||
}
|
||||
|
||||
return (double)sin(inputs[dir]+ret);
|
||||
}
|
||||
|
||||
double FractalSumNoise(genericNoise func, int iter, int len, double inputs[])
|
||||
{
|
||||
double ret = Noise(func, len, inputs);
|
||||
|
||||
int i = 0;
|
||||
for (i = 0 ; i < iter ; i++){
|
||||
double num = pow(2,iter);
|
||||
double scaled[len];
|
||||
int j = 0;
|
||||
for (j = 0; j < len; j++) {
|
||||
scaled[j] = inputs[len]*(num/i);
|
||||
}
|
||||
ret = ret + (i/num)*(Noise(func, len, scaled));
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
double FractalSumAbsNoise(genericNoise func, int iter, int len, double inputs[])
|
||||
{
|
||||
double ret = fabs(Noise(func, len, inputs));
|
||||
|
||||
int i = 0;
|
||||
for (i = 0 ; i < iter ; i++){
|
||||
double num = pow(2,iter);
|
||||
double scaled[len];
|
||||
int j = 0;
|
||||
for (j = 0; j < len; j++) {
|
||||
scaled[j] = inputs[len]*(num/i);
|
||||
}
|
||||
ret = ret + (i/num)*fabs(Noise(func, len, scaled));
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
int gradients3d[12][3] = {{1,1,0},{-1,1,0},{1,-1,0},{-1,-1,0},
|
||||
{1,0,1},{-1,0,1},{1,0,-1},{-1,0,-1},
|
||||
{0,1,1},{0,-1,1},{0,1,-1},{0,-1,-1}};
|
||||
int gradients4d[32][4] = {{0,1,1,1}, {0,1,1,-1}, {0,1,-1,1}, {0,1,-1,-1},
|
||||
{0,-1,1,1}, {0,-1,1,-1}, {0,-1,-1,1}, {0,-1,-1,-1},
|
||||
{1,0,1,1}, {1,0,1,-1}, {1,0,-1,1}, {1,0,-1,-1},
|
||||
{-1,0,1,1}, {-1,0,1,-1}, {-1,0,-1,1}, {-1,0,-1,-1},
|
||||
{1,1,0,1}, {1,1,0,-1}, {1,-1,0,1}, {1,-1,0,-1},
|
||||
{-1,1,0,1}, {-1,1,0,-1}, {-1,-1,0,1}, {-1,-1,0,-1},
|
||||
{1,1,1,0}, {1,1,-1,0}, {1,-1,1,0}, {1,-1,-1,0},
|
||||
{-1,1,1,0}, {-1,1,-1,0}, {-1,-1,1,0}, {-1,-1,-1,0}};
|
||||
int p[256] = {151,160,137,91,90,15,
|
||||
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
|
||||
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
|
||||
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
|
||||
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
|
||||
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
|
||||
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
|
||||
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
|
||||
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
|
||||
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
|
||||
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
|
||||
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
|
||||
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180};
|
||||
|
||||
int perm[512];
|
||||
|
||||
static void con() __attribute__((constructor));
|
||||
|
||||
void con() {
|
||||
int i = 0;
|
||||
for (i = 0 ; i < 255 ; i++) {
|
||||
perm[i] = p[i];
|
||||
perm[i+256] = p[i];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int simplex[64][4] = {
|
||||
{0,1,2,3},{0,1,3,2},{0,0,0,0},{0,2,3,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,2,3,0},
|
||||
{0,2,1,3},{0,0,0,0},{0,3,1,2},{0,3,2,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,3,2,0},
|
||||
{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},
|
||||
{1,2,0,3},{0,0,0,0},{1,3,0,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,3,0,1},{2,3,1,0},
|
||||
{1,0,2,3},{1,0,3,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,0,3,1},{0,0,0,0},{2,1,3,0},
|
||||
{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},
|
||||
{2,0,1,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,0,1,2},{3,0,2,1},{0,0,0,0},{3,1,2,0},
|
||||
{2,1,0,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,1,0,2},{0,0,0,0},{3,2,0,1},{3,2,1,0}};
|
||||
|
||||
const double e = 2.71828182845904523536;
|
||||
const double PI = 3.14159265358979323846;
|
||||
|
||||
double Dot2D(int tbl[],double x,double y)
|
||||
{
|
||||
return tbl[0]*x + tbl[1]*y;
|
||||
}
|
||||
|
||||
double Dot3D(int tbl[],double x,double y,double z)
|
||||
{
|
||||
return tbl[0]*x + tbl[1]*y + tbl[2]*z;
|
||||
}
|
||||
|
||||
double Dot4D(int tbl[],double x,double y,double z,double w)
|
||||
{
|
||||
return tbl[0]*x + tbl[1]*y + tbl[2]*z + tbl[3]*w;
|
||||
}
|
||||
|
||||
double Noise2D(double xin, double yin)
|
||||
{
|
||||
double n0, n1, n2; // Noise contributions from the three corners
|
||||
// Skew the input space to determine which simplex cell we're in
|
||||
double F2 = 0.5*(sqrt(3.0)-1.0);
|
||||
double s = (xin+yin)*F2; // Hairy factor for 2D
|
||||
int i = floor(xin+s);
|
||||
int j = floor(yin+s);
|
||||
double G2 = (3.0-sqrt(3.0))/6.0;
|
||||
|
||||
double t = (i+j)*G2;
|
||||
double X0 = i-t; // Unskew the cell origin back to (x,y) space
|
||||
double Y0 = j-t;
|
||||
double x0 = xin-X0; // The x,y distances from the cell origin
|
||||
double y0 = yin-Y0;
|
||||
|
||||
// For the 2D case, the simplex shape is an equilateral triangle.
|
||||
// Determine which simplex we are in.
|
||||
int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
|
||||
if(x0>y0){
|
||||
i1=1;
|
||||
j1=0; // lower triangle, XY order: (0,0)->(1,0)->(1,1)
|
||||
}
|
||||
else {
|
||||
i1=0;
|
||||
j1=1; // upper triangle, YX order: (0,0)->(0,1)->(1,1)
|
||||
}
|
||||
|
||||
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
|
||||
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
|
||||
// c = (3-sqrt(3))/6
|
||||
|
||||
double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
|
||||
double y1 = y0 - j1 + G2;
|
||||
double x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords
|
||||
double y2 = y0 - 1.0 + 2.0 * G2;
|
||||
|
||||
// Work out the hashed gradient indices of the three simplex corners
|
||||
int ii = i & 255;
|
||||
int jj = j & 255;
|
||||
int gi0 = perm[ii+perm[jj]] % 12;
|
||||
int gi1 = perm[ii+i1+perm[jj+j1]] % 12;
|
||||
int gi2 = perm[ii+1+perm[jj+1]] % 12;
|
||||
|
||||
// Calculate the contribution from the three corners
|
||||
double t0 = 0.5 - x0*x0-y0*y0;
|
||||
if (t0<0){
|
||||
n0 = 0.0;
|
||||
}
|
||||
else{
|
||||
t0 = t0 * t0;
|
||||
n0 = t0 * t0 * Dot2D(gradients3d[gi0], x0, y0); // (x,y) of Gradients3D used for 2D gradient
|
||||
}
|
||||
|
||||
double t1 = 0.5 - x1*x1-y1*y1;
|
||||
if (t1<0){
|
||||
n1 = 0.0;
|
||||
}
|
||||
else{
|
||||
t1 = t1*t1;
|
||||
n1 = t1 * t1 * Dot2D(gradients3d[gi1], x1, y1);
|
||||
}
|
||||
|
||||
double t2 = 0.5 - x2*x2-y2*y2;
|
||||
if (t2<0){
|
||||
n2 = 0.0;
|
||||
}
|
||||
else{
|
||||
t2 = t2*t2;
|
||||
n2 = t2 * t2 * Dot2D(gradients3d[gi2], x2, y2);
|
||||
}
|
||||
|
||||
// Add contributions from each corner to get the final noise value.
|
||||
// The result is scaled to return values in the localerval [-1,1].
|
||||
double ret = (70.0 * (n0 + n1 + n2));
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
double Noise3D(double xin, double yin,double zin)
|
||||
{
|
||||
double n0, n1, n2, n3; // Noise contributions from the four corners
|
||||
|
||||
// Skew the input space to determine which simplex cell we're in
|
||||
double F3 = 1.0/3.0;
|
||||
double s = (xin+yin+zin)*F3; // Very nice and simple skew factor for 3D
|
||||
int i = floor(xin+s);
|
||||
int j = floor(yin+s);
|
||||
int k = floor(zin+s);
|
||||
|
||||
double G3 = 1.0/6.0; // Very nice and simple unskew factor, too
|
||||
double t = (i+j+k)*G3;
|
||||
|
||||
double X0 = i-t; // Unskew the cell origin back to (x,y,z) space
|
||||
double Y0 = j-t;
|
||||
double Z0 = k-t;
|
||||
|
||||
double x0 = xin-X0; // The x,y,z distances from the cell origin
|
||||
double y0 = yin-Y0;
|
||||
double z0 = zin-Z0;
|
||||
|
||||
// For the 3D case, the simplex shape is a slightly irregular tetrahedron.
|
||||
// Determine which simplex we are in.
|
||||
int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords
|
||||
int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords
|
||||
|
||||
if (x0>=y0){
|
||||
if (y0>=z0){
|
||||
i1=1; j1=0; k1=0; i2=1; j2=1; k2=0; // X Y Z order
|
||||
}
|
||||
else if (x0>=z0){
|
||||
i1=1; j1=0; k1=0; i2=1; j2=0; k2=1; // X Z Y order
|
||||
}
|
||||
else{
|
||||
i1=0; j1=0; k1=1; i2=1; j2=0; k2=1; // Z X Y order
|
||||
}
|
||||
}
|
||||
else{ // x0<y0
|
||||
if (y0<z0){
|
||||
i1=0; j1=0; k1=1; i2=0; j2=1; k2=1; // Z Y X order
|
||||
}
|
||||
else if (x0<z0){
|
||||
i1=0; j1=1; k1=0; i2=0; j2=1; k2=1; // Y Z X order
|
||||
}
|
||||
else{
|
||||
i1=0; j1=1; k1=0; i2=1; j2=1; k2=0; // Y X Z order
|
||||
}
|
||||
}
|
||||
|
||||
// A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
|
||||
// a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
|
||||
// a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
|
||||
// c = 1/6.
|
||||
|
||||
double x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords
|
||||
double y1 = y0 - j1 + G3;
|
||||
double z1 = z0 - k1 + G3;
|
||||
|
||||
double x2 = x0 - i2 + 2.0*G3; // Offsets for third corner in (x,y,z) coords
|
||||
double y2 = y0 - j2 + 2.0*G3;
|
||||
double z2 = z0 - k2 + 2.0*G3;
|
||||
|
||||
double x3 = x0 - 1.0 + 3.0*G3; // Offsets for last corner in (x,y,z) coords
|
||||
double y3 = y0 - 1.0 + 3.0*G3;
|
||||
double z3 = z0 - 1.0 + 3.0*G3;
|
||||
|
||||
// Work out the hashed gradient indices of the four simplex corners
|
||||
int ii = i & 255;
|
||||
int jj = j & 255;
|
||||
int kk = k & 255;
|
||||
|
||||
int gi0 = perm[ii+perm[jj+perm[kk]]] % 12;
|
||||
int gi1 = perm[ii+i1+perm[jj+j1+perm[kk+k1]]] % 12;
|
||||
int gi2 = perm[ii+i2+perm[jj+j2+perm[kk+k2]]] % 12;
|
||||
int gi3 = perm[ii+1+perm[jj+1+perm[kk+1]]] % 12;
|
||||
|
||||
// Calculate the contribution from the four corners
|
||||
double t0 = 0.5 - x0*x0 - y0*y0 - z0*z0;
|
||||
|
||||
if (t0<0){
|
||||
n0 = 0.0;
|
||||
}
|
||||
else {
|
||||
t0 = t0*t0;
|
||||
n0 = t0 * t0 * Dot3D(gradients3d[gi0], x0, y0, z0);
|
||||
}
|
||||
|
||||
double t1 = 0.5 - x1*x1 - y1*y1 - z1*z1;
|
||||
|
||||
if (t1<0){
|
||||
n1 = 0.0;
|
||||
}
|
||||
else{
|
||||
t1 = t1*t1;
|
||||
n1 = t1 * t1 * Dot3D(gradients3d[gi1], x1, y1, z1);
|
||||
}
|
||||
|
||||
double t2 = 0.5 - x2*x2 - y2*y2 - z2*z2;
|
||||
|
||||
if (t2<0){
|
||||
n2 = 0.0;
|
||||
}
|
||||
else{
|
||||
t2 = t2*t2;
|
||||
n2 = t2 * t2 * Dot3D(gradients3d[gi2], x2, y2, z2);
|
||||
}
|
||||
|
||||
double t3 = 0.5 - x3*x3 - y3*y3 - z3*z3;
|
||||
|
||||
if (t3<0){
|
||||
n3 = 0.0;
|
||||
}
|
||||
else{
|
||||
t3 = t3*t3;
|
||||
n3 = t3 * t3 * Dot3D(gradients3d[gi3], x3, y3, z3);
|
||||
}
|
||||
|
||||
|
||||
// Add contributions from each corner to get the final noise value.
|
||||
// The result is scaled to stay just inside [-1,1]
|
||||
double retval = 32.0*(n0 + n1 + n2 + n3);
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
double Noise4D(double x,double y,double z,double w)
|
||||
{
|
||||
// The skewing and unskewing factors are hairy again for the 4D case
|
||||
double F4 = (sqrt(5.0)-1.0)/4.0;
|
||||
double G4 = (5.0-sqrt(5.0))/20.0;
|
||||
double n0, n1, n2, n3, n4; // Noise contributions from the five corners
|
||||
// Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
|
||||
double s = (x + y + z + w) * F4; // Factor for 4D skewing
|
||||
int i = floor(x + s);
|
||||
int j = floor(y + s);
|
||||
int k = floor(z + s);
|
||||
int l = floor(w + s);
|
||||
double t = (i + j + k + l) * G4; // Factor for 4D unskewing
|
||||
double X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
|
||||
double Y0 = j - t;
|
||||
double Z0 = k - t;
|
||||
double W0 = l - t;
|
||||
double x0 = x - X0; // The x,y,z,w distances from the cell origin
|
||||
double y0 = y - Y0;
|
||||
double z0 = z - Z0;
|
||||
double w0 = w - W0;
|
||||
// For the 4D case, the simplex is a 4D shape I won't even try to describe.
|
||||
// To find out which of the 24 possible simplices we're in, we need to
|
||||
// determine the magnitude ordering of x0, y0, z0 and w0.
|
||||
// The method below is a good way of finding the ordering of x,y,z,w and
|
||||
// then find the correct traversal order for the simplex we’re in.
|
||||
// First, six pair-wise comparisons are performed between each possible pair
|
||||
// of the four coordinates, and the results are used to add up binary bits
|
||||
// for an localeger index.
|
||||
int c1 = (x0 > y0) ? 32 : 1;
|
||||
int c2 = (x0 > z0) ? 16 : 1;
|
||||
int c3 = (y0 > z0) ? 8 : 1;
|
||||
int c4 = (x0 > w0) ? 4 : 1;
|
||||
int c5 = (y0 > w0) ? 2 : 1;
|
||||
int c6 = (z0 > w0) ? 1 : 1;
|
||||
int c = c1 + c2 + c3 + c4 + c5 + c6;
|
||||
int i1, j1, k1, l1; // The localeger offsets for the second simplex corner
|
||||
int i2, j2, k2, l2; // The localeger offsets for the third simplex corner
|
||||
int i3, j3, k3, l3; // The localeger offsets for the fourth simplex corner
|
||||
|
||||
// simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
|
||||
// Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
|
||||
// impossible. Only the 24 indices which have non-zero entries make any sense.
|
||||
// We use a thresholding to set the coordinates in turn from the largest magnitude.
|
||||
// The number 3 in the "simplex" array is at the position of the largest coordinate.
|
||||
|
||||
i1 = simplex[c][0]>=3 ? 1 : 0;
|
||||
j1 = simplex[c][1]>=3 ? 1 : 0;
|
||||
k1 = simplex[c][2]>=3 ? 1 : 0;
|
||||
l1 = simplex[c][3]>=3 ? 1 : 0;
|
||||
// The number 2 in the "simplex" array is at the second largest co:dinate.
|
||||
i2 = simplex[c][0]>=2 ? 1 : 0;
|
||||
j2 = simplex[c][1]>=2 ? 1 : 0;
|
||||
k2 = simplex[c][2]>=2 ? 1 : 0;
|
||||
l2 = simplex[c][3]>=2 ? 1 : 0;
|
||||
// The number 1 in the "simplex" array is at the second smallest co:dinate.
|
||||
i3 = simplex[c][0]>=1 ? 1 : 0;
|
||||
j3 = simplex[c][1]>=1 ? 1 : 0;
|
||||
k3 = simplex[c][2]>=1 ? 1 : 0;
|
||||
l3 = simplex[c][3]>=1 ? 1 : 0;
|
||||
// The fifth corner has all coordinate offsets = 1, so no need to look that up.
|
||||
double x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
|
||||
double y1 = y0 - j1 + G4;
|
||||
double z1 = z0 - k1 + G4;
|
||||
double w1 = w0 - l1 + G4;
|
||||
double x2 = x0 - i2 + 2.0*G4; // Offsets for third corner in (x,y,z,w) coords
|
||||
double y2 = y0 - j2 + 2.0*G4;
|
||||
double z2 = z0 - k2 + 2.0*G4;
|
||||
double w2 = w0 - l2 + 2.0*G4;
|
||||
double x3 = x0 - i3 + 3.0*G4; // Offsets for fourth corner in (x,y,z,w) coords
|
||||
double y3 = y0 - j3 + 3.0*G4;
|
||||
double z3 = z0 - k3 + 3.0*G4;
|
||||
double w3 = w0 - l3 + 3.0*G4;
|
||||
double x4 = x0 - 1.0 + 4.0*G4; // Offsets for last corner in (x,y,z,w) coords
|
||||
double y4 = y0 - 1.0 + 4.0*G4;
|
||||
double z4 = z0 - 1.0 + 4.0*G4;
|
||||
double w4 = w0 - 1.0 + 4.0*G4;
|
||||
|
||||
// Work out the hashed gradient indices of the five simplex corners
|
||||
int ii = i & 255;
|
||||
int jj = j & 255;
|
||||
int kk = k & 255;
|
||||
int ll = l & 255;
|
||||
int gi0 = perm[ii+perm[jj+perm[kk+perm[ll]]]] % 32;
|
||||
int gi1 = perm[ii+i1+perm[jj+j1+perm[kk+k1+perm[ll+l1]]]] % 32;
|
||||
int gi2 = perm[ii+i2+perm[jj+j2+perm[kk+k2+perm[ll+l2]]]] % 32;
|
||||
int gi3 = perm[ii+i3+perm[jj+j3+perm[kk+k3+perm[ll+l3]]]] % 32;
|
||||
int gi4 = perm[ii+1+perm[jj+1+perm[kk+1+perm[ll+1]]]] % 32;
|
||||
|
||||
|
||||
// Calculate the contribution from the five corners
|
||||
double t0 = 0.5 - x0*x0 - y0*y0 - z0*z0 - w0*w0;
|
||||
if (t0<0){
|
||||
n0 = 0.0;
|
||||
}
|
||||
else{
|
||||
t0 = t0*t0;
|
||||
n0 = t0 * t0 * Dot4D(gradients4d[gi0], x0, y0, z0, w0);
|
||||
}
|
||||
|
||||
double t1 = 0.5 - x1*x1 - y1*y1 - z1*z1 - w1*w1;
|
||||
if (t1<0){
|
||||
n1 = 0.0;
|
||||
}
|
||||
else{
|
||||
t1 = t1*t1;
|
||||
n1 = t1 * t1 * Dot4D(gradients4d[gi1], x1, y1, z1, w1);
|
||||
}
|
||||
|
||||
double t2 = 0.5 - x2*x2 - y2*y2 - z2*z2 - w2*w2;
|
||||
if (t2<0){
|
||||
n2 = 0.0;
|
||||
}
|
||||
else{
|
||||
t2 = t2*t2;
|
||||
n2 = t2 * t2 * Dot4D(gradients4d[gi2], x2, y2, z2, w2);
|
||||
}
|
||||
|
||||
double t3 = 0.5 - x3*x3 - y3*y3 - z3*z3 - w3*w3;
|
||||
if (t3<0){
|
||||
n3 = 0.0;
|
||||
}
|
||||
else {
|
||||
t3 = t3*t3;
|
||||
n3 = t3 * t3 * Dot4D(gradients4d[gi3], x3, y3, z3, w3);
|
||||
}
|
||||
|
||||
double t4 = 0.5 - x4*x4 - y4*y4 - z4*z4 - w4*w4;
|
||||
if (t4<0){
|
||||
n4 = 0.0;
|
||||
}
|
||||
else{
|
||||
t4 = t4*t4;
|
||||
n4 = t4 * t4 * Dot4D(gradients4d[gi4], x4, y4, z4, w4);
|
||||
}
|
||||
|
||||
// Sum up and scale the result to cover the range [-1,1]
|
||||
|
||||
double retval = 27.0 * (n0 + n1 + n2 + n3 + n4);
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
double GBlur2D(double stdDev, double x, double y)
|
||||
{
|
||||
if (fabs(stdDev)<=0.0) { return 0; }
|
||||
|
||||
double pwr = ((pow(x,2)+pow(y,2))/(2*pow(stdDev,2)))*-1;
|
||||
double ret = (1/(2*PI*pow(stdDev,2)))*pow(e, pwr);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
double GBlur1D(double stdDev, double x)
|
||||
{
|
||||
if (fabs(stdDev)<=0.0) { return 0; }
|
||||
|
||||
double pwr = (pow(x,2)/(2*pow(stdDev,2)))*-1;
|
||||
double ret = (1/(sqrt(2*PI)*stdDev))*pow(e, pwr);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
double octave_3d(double x, double y, double z, int octaves, double persistence)
|
||||
{
|
||||
double total = 0;
|
||||
double frequency = 1;
|
||||
double amplitude = 1;
|
||||
double max = 0;
|
||||
for (int i = 0; i < octaves; i++) {
|
||||
total += Noise3D(x*frequency, y*frequency, z*frequency) * amplitude;
|
||||
max += amplitude;
|
||||
amplitude *= persistence;
|
||||
frequency *= 2;
|
||||
}
|
||||
return total/max;
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//externs made available by simplex.c
|
||||
|
||||
#ifndef SIMPLEX_H_INCLUDED
|
||||
#define SIMPLEX_H_INCLUDED
|
||||
|
||||
#define SIMPLEX_X 0
|
||||
#define SIMPLEX_Y 1
|
||||
#define SIMPLEX_Z 2
|
||||
#define SIMPLEX_W 3
|
||||
|
||||
typedef double (*noise2Dptr)(double, double);
|
||||
typedef double (*noise3Dptr)(double, double, double);
|
||||
typedef double (*noise4Dptr)(double, double, double, double);
|
||||
|
||||
typedef double (*noiseNDptr)(int, double[]);
|
||||
|
||||
typedef union NoiseUnion {
|
||||
noise2Dptr p2;
|
||||
noise3Dptr p3;
|
||||
noise4Dptr p4;
|
||||
noiseNDptr pn;
|
||||
} genericNoise;
|
||||
|
||||
double Noise2D(double x, double y);
|
||||
double Noise3D(double x, double y, double z);
|
||||
double Noise4D(double x, double y, double z, double w);
|
||||
|
||||
double GBlur1D(double stdDev, double x);
|
||||
double GBlur2D(double stdDev, double x, double y);
|
||||
|
||||
double Noise(genericNoise func, int len, double args[]);
|
||||
|
||||
double TurbulentNoise(genericNoise func, int direction, int iterations, int len, double args[]);
|
||||
double FractalSumNoise(genericNoise func, int iterations, int len, double args[]);
|
||||
double FractalSumAbsNoise(genericNoise func, int iterations, int len, double args[]);
|
||||
|
||||
double octave_3d(double x, double y, double z, int octaves, double persistence);
|
||||
|
||||
#endif
|
||||
450
source/spline.c
450
source/spline.c
@@ -1,450 +0,0 @@
|
||||
#include "spline.h"
|
||||
#include "stb_ds.h"
|
||||
#include <float.h>
|
||||
#include "transform.h"
|
||||
#include "math.h"
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
Cubic Spline Basis Matrices
|
||||
------------------------------------------------------------------------- */
|
||||
static const HMM_Mat4 cubic_hermite_m = {
|
||||
2, -2, 1, 1,
|
||||
-3, 3, -2, -1,
|
||||
0, 0, 1, 0,
|
||||
1, 0, 0, 0
|
||||
};
|
||||
|
||||
static const HMM_Mat4 cubic_hermite_dm = {
|
||||
0, 0, 0, 0,
|
||||
6, -6, 3, 3,
|
||||
-6, 6, -4, -2,
|
||||
0, 0, 1, 0
|
||||
};
|
||||
|
||||
static const HMM_Mat4 cubic_hermite_ddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
12, -12, 6, 6,
|
||||
-6, 6, -4, -2
|
||||
};
|
||||
|
||||
static const HMM_Mat4 cubic_hermite_dddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
12, -12, 6, 6
|
||||
};
|
||||
|
||||
static const HMM_Mat4 b_spline_m = {
|
||||
-1.0f/6, 3.0f/6, -3.0f/6, 1.0f,
|
||||
3.0f/6, -6.0f/6, 3.0f/6, 0.0f,
|
||||
-3.0f/6, 0.0f, 3.0f/6, 0.0f,
|
||||
1.0f/6, 4.0f/6, 1.0f/6, 0.0f
|
||||
};
|
||||
|
||||
static const HMM_Mat4 b_spline_dm = {
|
||||
0, 0, 0, 0,
|
||||
-3.0f/6, 9.0f/6, -9.0f/6, 3.0f,
|
||||
6.0f/6, -12.0f/6, 6.0f/6, 0.0f,
|
||||
-3.0f/6, 0.0f, 3.0f/6, 0.0f
|
||||
};
|
||||
|
||||
static const HMM_Mat4 b_spline_ddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
-6.0f/6, 18.0f/6, -18.0f/6, 6.0f,
|
||||
6.0f/6, -12.0f/6, 6.0f/6, 0.0f
|
||||
};
|
||||
|
||||
static const HMM_Mat4 b_spline_dddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
-6.0f/6, 18.0f/6, -18.0f/6, 6.0f
|
||||
};
|
||||
|
||||
static const HMM_Mat4 bezier_m = {
|
||||
-1, 3, -3, 1,
|
||||
3, -6, 3, 0,
|
||||
-3, 3, 0, 0,
|
||||
1, 0, 0, 0
|
||||
};
|
||||
|
||||
static const HMM_Mat4 bezier_dm = {
|
||||
0, 0, 0, 0,
|
||||
-3, 9, -9, 3,
|
||||
6, -12, 6, 0,
|
||||
-3, 3, 0, 0
|
||||
};
|
||||
|
||||
static const HMM_Mat4 bezier_ddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
-6, 18, -18, 6,
|
||||
6, -12, 6, 0
|
||||
};
|
||||
|
||||
static const HMM_Mat4 bezier_dddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
-6, 18, -18, 6
|
||||
};
|
||||
|
||||
/* Catmull–Rom (with tension = 0.5 by default) */
|
||||
#define CAT_S 0.5f
|
||||
|
||||
static const HMM_Mat4 catmull_rom_m = {
|
||||
-CAT_S, 2-CAT_S, CAT_S-2, CAT_S,
|
||||
2*CAT_S, CAT_S-3, 3-2*CAT_S, -CAT_S,
|
||||
-CAT_S, 0, CAT_S, 0,
|
||||
0, 1, 0, 0
|
||||
};
|
||||
|
||||
static const HMM_Mat4 catmull_rom_dm = {
|
||||
0, 0, 0, 0,
|
||||
-3*CAT_S, 9*CAT_S, -9*CAT_S, 3*CAT_S,
|
||||
4*CAT_S, -10*CAT_S, 8*CAT_S, -2*CAT_S,
|
||||
-CAT_S, 0, CAT_S, 0
|
||||
};
|
||||
|
||||
static const HMM_Mat4 catmull_rom_ddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
-9*CAT_S, 18*CAT_S, -18*CAT_S, 6*CAT_S,
|
||||
4*CAT_S, -10*CAT_S, 8*CAT_S, -2*CAT_S
|
||||
};
|
||||
|
||||
static const HMM_Mat4 catmull_rom_dddm = {
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
-9*CAT_S, 18*CAT_S, -18*CAT_S, 6*CAT_S
|
||||
};
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
Core “C·T” multiplication: [ t^3, t^2, t, 1 ] * C
|
||||
------------------------------------------------------------------------- */
|
||||
HMM_Vec4 spline_CT(HMM_Mat4 *C, float t)
|
||||
{
|
||||
float t2 = t * t;
|
||||
float t3 = t2 * t;
|
||||
HMM_Vec4 T = { t3, t2, t, 1.0f };
|
||||
return HMM_MulM4V4(*C, T);
|
||||
}
|
||||
|
||||
/* Construct the “geometry matrix” G from four 2D points, then multiply by B */
|
||||
HMM_Mat4 make_C(const HMM_Vec2 *p, const HMM_Mat4 *B)
|
||||
{
|
||||
HMM_Mat4 G = HMM_M4(); // Zeroed out
|
||||
// Only fill XY of each column; if you are storing 3D in HMM_Vec4, adapt as needed
|
||||
G.Columns[0].XY = p[0];
|
||||
G.Columns[1].XY = p[1];
|
||||
G.Columns[2].XY = p[2];
|
||||
G.Columns[3].XY = p[3];
|
||||
|
||||
return HMM_MulM4(G, *B);
|
||||
}
|
||||
|
||||
/* Evaluate a single-segment cubic spline at parameter d in [0,1].
|
||||
p must be 4 control points, m is the cubic basis matrix. */
|
||||
HMM_Vec2 cubic_spline_d(HMM_Vec2 *p, HMM_Mat4 *m, float d)
|
||||
{
|
||||
HMM_Mat4 C = make_C(p, m);
|
||||
HMM_Vec4 v4 = spline_CT(&C, d);
|
||||
return v4.XY;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
Convenience single-segment functions for each basis
|
||||
(pos / tan / curv / wig all require the appropriate matrix)
|
||||
Typically you pass p[0..3] as the 4 relevant control points.
|
||||
------------------------------------------------------------------------- */
|
||||
HMM_Vec2 cubic_hermite_pos(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&cubic_hermite_m, d); }
|
||||
HMM_Vec2 cubic_hermite_tan(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&cubic_hermite_dm, d); }
|
||||
HMM_Vec2 cubic_hermite_curv(HMM_Vec2 *p, float d){ return cubic_spline_d(p, (HMM_Mat4 *)&cubic_hermite_ddm, d); }
|
||||
HMM_Vec2 cubic_hermite_wig(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&cubic_hermite_dddm, d); }
|
||||
|
||||
HMM_Vec2 b_spline_pos(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&b_spline_m, d); }
|
||||
HMM_Vec2 b_spline_tan(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&b_spline_dm, d); }
|
||||
HMM_Vec2 b_spline_curv(HMM_Vec2 *p, float d){ return cubic_spline_d(p, (HMM_Mat4 *)&b_spline_ddm, d); }
|
||||
HMM_Vec2 b_spline_wig(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&b_spline_dddm, d); }
|
||||
|
||||
HMM_Vec2 bezier_pos(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&bezier_m, d); }
|
||||
HMM_Vec2 bezier_tan(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&bezier_dm, d); }
|
||||
HMM_Vec2 bezier_curv(HMM_Vec2 *p, float d){ return cubic_spline_d(p, (HMM_Mat4 *)&bezier_ddm, d); }
|
||||
HMM_Vec2 bezier_wig(HMM_Vec2 *p, float d) { return cubic_spline_d(p, (HMM_Mat4 *)&bezier_dddm, d); }
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
Multi-segment sampling (“spline_v2”) for uniform division
|
||||
------------------------------------------------------------------------- */
|
||||
HMM_Vec2 *spline_v2(HMM_Vec2 *p, HMM_Mat4 *m, int segs)
|
||||
{
|
||||
// For a single 4-point segment, produce 'segs' points along [0..1).
|
||||
// If you want the final 1.0 also, you can do <= 1.0 in the loop, etc.
|
||||
HMM_Vec2 *ret = NULL;
|
||||
if (segs < 2) return NULL;
|
||||
|
||||
HMM_Mat4 C = make_C(p, m);
|
||||
float s = 1.0f / (float)segs;
|
||||
for (int i = 0; i <= segs; i++)
|
||||
{
|
||||
float t = s * i;
|
||||
arrput(ret, spline_CT(&C, t).XY);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
Adaptive subdivision by min segment length
|
||||
(spline2d_min_seg) – for a single 4-point segment
|
||||
------------------------------------------------------------------------- */
|
||||
HMM_Vec2 *spline2d_min_seg(float u0, float u1, float min_seg, HMM_Mat4 *C, HMM_Vec2 *ret)
|
||||
{
|
||||
HMM_Vec2 a = spline_CT(C, u0).XY;
|
||||
HMM_Vec2 b = spline_CT(C, u1).XY;
|
||||
if (HMM_DistV2(a, b) > min_seg)
|
||||
{
|
||||
float umid = 0.5f * (u0 + u1);
|
||||
spline2d_min_seg(u0, umid, min_seg, C, ret);
|
||||
spline2d_min_seg(umid, u1, min_seg, C, ret);
|
||||
}
|
||||
else
|
||||
{
|
||||
// We push 'b' so that we don't double-push 'a'
|
||||
arrput(ret, b);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Example: catmull_rom_min_seg -> subdiv for catmull–rom over one segment
|
||||
You would decide how to pick the 4 points from a,b,c,d, then run. */
|
||||
HMM_Vec2 *catmull_rom_min_seg(HMM_Vec2 *a, HMM_Vec2 *b, HMM_Vec2 *c, HMM_Vec2 *d, float min_seg)
|
||||
{
|
||||
HMM_Vec2 *ret = NULL;
|
||||
arrsetcap(ret, 1000);
|
||||
|
||||
// Build the matrix for these four points
|
||||
HMM_Vec2 p[4] = { *a, *b, *c, *d };
|
||||
HMM_Mat4 C = make_C(p, &catmull_rom_m);
|
||||
|
||||
// Always push the starting point (b in your original code was the second ctrl point, etc.)
|
||||
// But usually we want the first actual point in the segment:
|
||||
arrput(ret, cubic_spline_d(p, (HMM_Mat4*)&catmull_rom_m, 0.0f));
|
||||
|
||||
// Actually subdiv
|
||||
spline2d_min_seg(0.0f, 1.0f, min_seg, &C, ret);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
Adaptive subdivision by “max angle” proxy
|
||||
(spline2d_min_angle_2) – for single 4-point segment
|
||||
------------------------------------------------------------------------- */
|
||||
HMM_Vec2 *spline2d_min_angle_2(float u0, float u1, float max_angle, HMM_Mat4 *C, HMM_Vec2 *arr)
|
||||
{
|
||||
// Heuristic approach: sample midpoints, check “chord vs polyline” difference
|
||||
float ustep = (u1 - u0) / 4.0f;
|
||||
float um0 = u0 + ustep;
|
||||
float um1 = u0 + 2.0f * ustep;
|
||||
float um2 = u0 + 3.0f * ustep;
|
||||
|
||||
HMM_Vec2 m0 = spline_CT(C, um0).XY;
|
||||
HMM_Vec2 m1 = spline_CT(C, um1).XY;
|
||||
HMM_Vec2 m2 = spline_CT(C, um2).XY;
|
||||
|
||||
HMM_Vec2 a = spline_CT(C, u0).XY;
|
||||
HMM_Vec2 b = spline_CT(C, u1).XY;
|
||||
|
||||
// Chord = distance from a to b
|
||||
float chord = HMM_DistV2(a, b);
|
||||
// Polyline = a->m0->m1->m2->b
|
||||
float cdist = HMM_DistV2(a, m0)
|
||||
+ HMM_DistV2(m0, m1)
|
||||
+ HMM_DistV2(m1, m2)
|
||||
+ HMM_DistV2(m2, b);
|
||||
|
||||
// If the difference is bigger than some threshold (max_angle),
|
||||
// subdivide. Otherwise, keep it.
|
||||
if ((cdist - chord) > max_angle)
|
||||
{
|
||||
arr = spline2d_min_angle_2(u0, um1, max_angle, C, arr);
|
||||
arr = spline2d_min_angle_2(um1, u1, max_angle, C, arr);
|
||||
}
|
||||
else
|
||||
{
|
||||
// We accept “b” as a new point
|
||||
arrput(arr, b);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
HMM_Vec2 *spline_min_angle(HMM_Vec2 *p, const HMM_Mat4 *B, float min_angle, HMM_Vec2 *arr)
|
||||
{
|
||||
HMM_Mat4 C = make_C(p, B);
|
||||
// Subdivide from 0..1
|
||||
float u0 = 0.0f, u1 = 1.0f;
|
||||
// Usually we want to ensure the start point is in arr:
|
||||
HMM_Vec2 startPt = spline_CT(&C, u0).XY;
|
||||
if (arrlen(arr) == 0) {
|
||||
arrput(arr, startPt);
|
||||
}
|
||||
// Now subdiv for angle
|
||||
arr = spline2d_min_angle_2(u0, u1, min_angle, &C, arr);
|
||||
return arr;
|
||||
}
|
||||
|
||||
/* Example: catmull_rom_ma_v2 – uses “min_angle” over multiple segments
|
||||
Each 4 consecutive points is one segment. We do this for all segments. */
|
||||
HMM_Vec2 *catmull_rom_ma_v2(HMM_Vec2 *cp, float ma)
|
||||
{
|
||||
int n = arrlen(cp);
|
||||
if (n < 4) return NULL;
|
||||
|
||||
HMM_Vec2 *ret = NULL;
|
||||
// Pre-allocate some capacity
|
||||
arrsetcap(ret, (n-3) * 8);
|
||||
|
||||
// For convenience, let's always ensure we push the very first point:
|
||||
arrput(ret, cp[0]);
|
||||
|
||||
// For each segment [i, i+1, i+2, i+3], adaptively sample
|
||||
// Then move i by 1 each time if you want Catmull–Rom in “overlapped” fashion
|
||||
for (int i = 0; i < n - 3; i++)
|
||||
{
|
||||
// p[i..i+3]
|
||||
ret = spline_min_angle(&cp[i], &catmull_rom_m, ma, ret);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Example: do the same with Bezier in “cubic-bezier” style (control points in groups of 3 “handles”) */
|
||||
HMM_Vec2 *bezier_cb_ma_v2(HMM_Vec2 *cp, float ma)
|
||||
{
|
||||
int n = arrlen(cp);
|
||||
// Typically a Bezier “chain” would use control points in multiples of 3 + 1, etc.
|
||||
// E.g. p[0] is start, p[1..3] are control handles for first segment, then p[3..6] for second, etc.
|
||||
// Adjust logic to your liking.
|
||||
if (n < 4) return NULL;
|
||||
|
||||
HMM_Vec2 *ret = NULL;
|
||||
arrsetcap(ret, (n/3) * 8);
|
||||
|
||||
// First point
|
||||
arrput(ret, cp[0]);
|
||||
|
||||
// For each cubic Bezier segment: i += 3
|
||||
for (int i = 0; i < n - 3; i += 3)
|
||||
{
|
||||
ret = spline_min_angle(&cp[i], &bezier_m, ma, ret);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
static HMM_Vec2 catmull_rom_query_internal(HMM_Vec2 *cp, float d, const HMM_Mat4 *M)
|
||||
{
|
||||
int n = arrlen(cp);
|
||||
if (n < 4) return HMM_V2(0,0);
|
||||
|
||||
// Number of segments:
|
||||
int seg_count = n - 3;
|
||||
// Scale d in [0..1] -> which segment?
|
||||
float segf = d * seg_count;
|
||||
int seg_idx = (int) floorf(segf);
|
||||
if (seg_idx >= seg_count) seg_idx = seg_count - 1;
|
||||
if (seg_idx < 0) seg_idx = 0;
|
||||
|
||||
// Local parameter in [0..1]
|
||||
float u = segf - seg_idx;
|
||||
|
||||
// The control points for that segment are cp[ seg_idx .. seg_idx+3 ]
|
||||
return cubic_spline_d(cp + seg_idx, (HMM_Mat4 *)M, u);
|
||||
}
|
||||
|
||||
HMM_Vec2 catmull_rom_pos(HMM_Vec2 *cp, float d)
|
||||
{
|
||||
return catmull_rom_query_internal(cp, d, &catmull_rom_m);
|
||||
}
|
||||
HMM_Vec2 catmull_rom_tan(HMM_Vec2 *cp, float d)
|
||||
{
|
||||
return catmull_rom_query_internal(cp, d, &catmull_rom_dm);
|
||||
}
|
||||
HMM_Vec2 catmull_rom_curv(HMM_Vec2 *cp, float d)
|
||||
{
|
||||
return catmull_rom_query_internal(cp, d, &catmull_rom_ddm);
|
||||
}
|
||||
HMM_Vec2 catmull_rom_wig(HMM_Vec2 *cp, float d)
|
||||
{
|
||||
return catmull_rom_query_internal(cp, d, &catmull_rom_dddm);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
Approximate length of a single 4-point cubic spline segment by
|
||||
numeric integration (or sampling) of the velocity magnitude.
|
||||
“spline_seglen” below does a quick sampling approach.
|
||||
------------------------------------------------------------------------- */
|
||||
float spline_seglen(float t0, float t1, int steps, HMM_Mat4 *Cd, HMM_Mat4 *C)
|
||||
{
|
||||
// Simple uniform sampling of the tangent magnitude
|
||||
float total = 0.0f;
|
||||
float dt = (t1 - t0) / (float) steps;
|
||||
for (int i = 0; i < steps; i++)
|
||||
{
|
||||
float t = t0 + (i + 0.5f) * dt; // midpoint rule
|
||||
// derivative at t
|
||||
HMM_Vec2 vel = spline_CT(Cd, t).XY;
|
||||
float speed = HMM_LenV2(vel);
|
||||
total += speed * dt;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/* Summation of lengths across all Catmull–Rom segments. */
|
||||
float catmull_rom_len(HMM_Vec2 *cp)
|
||||
{
|
||||
int stepsPerSegment = 64;
|
||||
float len = 0.0f;
|
||||
int n = arrlen(cp);
|
||||
if (n < 4) return 0.0f;
|
||||
|
||||
for (int i = 0; i < n - 3; i++)
|
||||
{
|
||||
// Build the position matrix & derivative matrix for this segment
|
||||
HMM_Mat4 C = make_C(&cp[i], &catmull_rom_m);
|
||||
HMM_Mat4 Cd = make_C(&cp[i], &catmull_rom_dm);
|
||||
// integrate from 0..1
|
||||
len += spline_seglen(0.0f, 1.0f, stepsPerSegment, &Cd, &C);
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
HMM_Vec2 catmull_rom_closest(HMM_Vec2 *cp, HMM_Vec2 p)
|
||||
{
|
||||
int n = arrlen(cp);
|
||||
if (n < 4) return p;
|
||||
|
||||
float bestDist = FLT_MAX;
|
||||
HMM_Vec2 bestPt = p;
|
||||
|
||||
int steps = 64; // more steps => more accurate
|
||||
for (int seg = 0; seg < n - 3; seg++)
|
||||
{
|
||||
// Build a single-segment matrix
|
||||
HMM_Vec2 segCP[4] = { cp[seg], cp[seg+1], cp[seg+2], cp[seg+3] };
|
||||
HMM_Mat4 C = make_C(segCP, &catmull_rom_m);
|
||||
for (int i = 0; i <= steps; i++)
|
||||
{
|
||||
float t = (float)i / steps;
|
||||
HMM_Vec2 pt = spline_CT(&C, t).XY;
|
||||
float dist = HMM_DistV2(p, pt);
|
||||
if (dist < bestDist)
|
||||
{
|
||||
bestDist = dist;
|
||||
bestPt = pt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestPt;
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
#ifndef SPLINE_H
|
||||
#define SPLINE_H
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
These were already in your original header:
|
||||
*/
|
||||
|
||||
// Adaptive Catmull–Rom in 2D / 3D / 4D (by minimum angle):
|
||||
HMM_Vec2 *catmull_rom_ma_v2(HMM_Vec2 *cp, float ma);
|
||||
HMM_Vec3 *catmull_rom_ma_v3(HMM_Vec3 *cp, float ma); /* not yet implemented in .c, placeholder */
|
||||
HMM_Vec4 *catmull_rom_ma_v4(HMM_Vec4 *cp, float ma); /* not yet implemented in .c, placeholder */
|
||||
|
||||
// Adaptive Bezier in 2D (by minimum angle):
|
||||
HMM_Vec2 *bezier_cb_ma_v2(HMM_Vec2 *cp, float ma);
|
||||
|
||||
// Generic “single-segment” query for 2D control points + basis matrix:
|
||||
HMM_Vec2 spline_query(HMM_Vec2 *cp, float d, HMM_Mat4 *basis);
|
||||
|
||||
// Catmull–Rom “entire spline” queries:
|
||||
HMM_Vec2 catmull_rom_pos(HMM_Vec2 *cp, float d); // position
|
||||
HMM_Vec2 catmull_rom_tan(HMM_Vec2 *cp, float d); // tangent
|
||||
HMM_Vec2 catmull_rom_curv(HMM_Vec2 *cp, float d); // curvature
|
||||
HMM_Vec2 catmull_rom_wig(HMM_Vec2 *cp, float d); // 3rd derivative (“wiggle”)
|
||||
|
||||
// Computes approximate length of a 2D Catmull–Rom spline:
|
||||
float catmull_rom_len(HMM_Vec2 *cp);
|
||||
|
||||
// Returns closest point on a 2D Catmull–Rom curve given an external 2D point `p`:
|
||||
HMM_Vec2 catmull_rom_closest(HMM_Vec2 *cp, HMM_Vec2 p);
|
||||
|
||||
|
||||
/*
|
||||
Additional convenience functions for *single-segment* cubic splines:
|
||||
|
||||
Each of these expects exactly 4 control points in `p[0..3]`,
|
||||
and a parameter t in [0..1]. They pick the appropriate matrix internally.
|
||||
*/
|
||||
|
||||
// Hermite:
|
||||
HMM_Vec2 cubic_hermite_pos(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 cubic_hermite_tan(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 cubic_hermite_curv(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 cubic_hermite_wig(HMM_Vec2 *p, float d);
|
||||
|
||||
// B-spline:
|
||||
HMM_Vec2 b_spline_pos(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 b_spline_tan(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 b_spline_curv(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 b_spline_wig(HMM_Vec2 *p, float d);
|
||||
|
||||
// Bezier:
|
||||
HMM_Vec2 bezier_pos(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 bezier_tan(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 bezier_curv(HMM_Vec2 *p, float d);
|
||||
HMM_Vec2 bezier_wig(HMM_Vec2 *p, float d);
|
||||
|
||||
|
||||
/*
|
||||
Uniform sampling of a *single* 4-point segment in 2D:
|
||||
Returns an array of points (stb_ds dynamic array).
|
||||
*/
|
||||
HMM_Vec2 *spline_v2(HMM_Vec2 *p, HMM_Mat4 *m, int segs);
|
||||
|
||||
/*
|
||||
Adaptive subdivision routines (single-segment) in 2D:
|
||||
- Subdivide by min segment length
|
||||
- Subdivide by “max angle” proxy
|
||||
*/
|
||||
HMM_Vec2 *spline2d_min_seg(float u0, float u1, float min_seg, HMM_Mat4 *C, HMM_Vec2 *ret);
|
||||
HMM_Vec2 *catmull_rom_min_seg(HMM_Vec2 *a, HMM_Vec2 *b, HMM_Vec2 *c, HMM_Vec2 *d, float min_seg);
|
||||
|
||||
HMM_Vec2 *spline2d_min_angle_2(float u0, float u1, float max_angle, HMM_Mat4 *C, HMM_Vec2 *arr);
|
||||
HMM_Vec2 *spline_min_angle(HMM_Vec2 *p, const HMM_Mat4 *B, float min_angle, HMM_Vec2 *arr);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* SPLINE_H */
|
||||
@@ -1,29 +0,0 @@
|
||||
#include "sprite.h"
|
||||
|
||||
sprite *make_sprite(void)
|
||||
{
|
||||
sprite *sprite = calloc(sizeof(*sprite),1);
|
||||
sprite->image = JS_NULL;
|
||||
return sprite;
|
||||
}
|
||||
|
||||
void sprite_free(JSRuntime *rt, sprite *sprite)
|
||||
{
|
||||
JS_FreeValueRT(rt,sprite->image);
|
||||
free(sprite);
|
||||
}
|
||||
|
||||
void sprite_apply(sprite *sp)
|
||||
{
|
||||
/* -------- rotation + skew → 2×2 affine matrix -------- */
|
||||
float rot = sp->rotation;
|
||||
HMM_Vec2 k = sp->skew;
|
||||
|
||||
float c = cosf(rot), s = sinf(rot);
|
||||
|
||||
sp->affine.Columns[0] = (HMM_Vec2){ .x = c + k.x * s,
|
||||
.y = k.y * c + s };
|
||||
sp->affine.Columns[1] = (HMM_Vec2){ .x = -s + k.x * c,
|
||||
.y = -k.y * s + c };
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
#ifndef SPRITE_H
|
||||
#define SPRITE_H
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
#include "cell.h"
|
||||
|
||||
struct sprite{
|
||||
HMM_Vec2 pos; // x,y coordinates of the sprite
|
||||
HMM_Vec2 center;
|
||||
HMM_Vec2 skew;
|
||||
HMM_Vec2 scale;
|
||||
float rotation;
|
||||
HMM_Mat2 affine;
|
||||
JSValue image; // the JS image
|
||||
int layer; // layer this sprite draws onto
|
||||
HMM_Vec4 color; // color in 0-1f
|
||||
};
|
||||
|
||||
typedef struct sprite sprite;
|
||||
|
||||
sprite *make_sprite(void);
|
||||
void sprite_free(JSRuntime *rt, sprite *sprite);
|
||||
void sprite_apply(sprite *sprite);
|
||||
|
||||
#endif
|
||||
7
source/thirdparty/cgltf/LICENSE
vendored
7
source/thirdparty/cgltf/LICENSE
vendored
@@ -1,7 +0,0 @@
|
||||
Copyright (c) 2018-2021 Johannes Kuhlmann
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
161
source/thirdparty/cgltf/README.md
vendored
161
source/thirdparty/cgltf/README.md
vendored
@@ -1,161 +0,0 @@
|
||||
# :diamond_shape_with_a_dot_inside: cgltf
|
||||
**Single-file/stb-style C glTF loader and writer**
|
||||
|
||||
[](https://github.com/jkuhlmann/cgltf/actions)
|
||||
|
||||
Used in: [bgfx](https://github.com/bkaradzic/bgfx), [Filament](https://github.com/google/filament), [gltfpack](https://github.com/zeux/meshoptimizer/tree/master/gltf), [raylib](https://github.com/raysan5/raylib), [Unigine](https://developer.unigine.com/en/docs/2.14.1/third_party?rlang=cpp#cgltf), and more!
|
||||
|
||||
## Usage: Loading
|
||||
Loading from file:
|
||||
```c
|
||||
#define CGLTF_IMPLEMENTATION
|
||||
#include "cgltf.h"
|
||||
|
||||
cgltf_options options = {0};
|
||||
cgltf_data* data = NULL;
|
||||
cgltf_result result = cgltf_parse_file(&options, "scene.gltf", &data);
|
||||
if (result == cgltf_result_success)
|
||||
{
|
||||
/* TODO make awesome stuff */
|
||||
cgltf_free(data);
|
||||
}
|
||||
```
|
||||
|
||||
Loading from memory:
|
||||
```c
|
||||
#define CGLTF_IMPLEMENTATION
|
||||
#include "cgltf.h"
|
||||
|
||||
void* buf; /* Pointer to glb or gltf file data */
|
||||
size_t size; /* Size of the file data */
|
||||
|
||||
cgltf_options options = {0};
|
||||
cgltf_data* data = NULL;
|
||||
cgltf_result result = cgltf_parse(&options, buf, size, &data);
|
||||
if (result == cgltf_result_success)
|
||||
{
|
||||
/* TODO make awesome stuff */
|
||||
cgltf_free(data);
|
||||
}
|
||||
```
|
||||
|
||||
Note that cgltf does not load the contents of extra files such as buffers or images into memory by default. You'll need to read these files yourself using URIs from `data.buffers[]` or `data.images[]` respectively.
|
||||
For buffer data, you can alternatively call `cgltf_load_buffers`, which will use `FILE*` APIs to open and read buffer files. This automatically decodes base64 data URIs in buffers. For data URIs in images, you will need to use `cgltf_load_buffer_base64`.
|
||||
|
||||
**For more in-depth documentation and a description of the public interface refer to the top of the `cgltf.h` file.**
|
||||
|
||||
## Usage: Writing
|
||||
When writing glTF data, you need a valid `cgltf_data` structure that represents a valid glTF document. You can construct such a structure yourself or load it using the loader functions described above. The writer functions do not deallocate any memory. So, you either have to do it manually or call `cgltf_free()` if you got the data by loading it from a glTF document.
|
||||
|
||||
Writing to file:
|
||||
```c
|
||||
#define CGLTF_IMPLEMENTATION
|
||||
#define CGLTF_WRITE_IMPLEMENTATION
|
||||
#include "cgltf_write.h"
|
||||
|
||||
cgltf_options options = {0};
|
||||
cgltf_data* data = /* TODO must be valid data */;
|
||||
cgltf_result result = cgltf_write_file(&options, "out.gltf", data);
|
||||
if (result != cgltf_result_success)
|
||||
{
|
||||
/* TODO handle error */
|
||||
}
|
||||
```
|
||||
|
||||
Writing to memory:
|
||||
```c
|
||||
#define CGLTF_IMPLEMENTATION
|
||||
#define CGLTF_WRITE_IMPLEMENTATION
|
||||
#include "cgltf_write.h"
|
||||
cgltf_options options = {0};
|
||||
cgltf_data* data = /* TODO must be valid data */;
|
||||
|
||||
cgltf_size size = cgltf_write(&options, NULL, 0, data);
|
||||
|
||||
char* buf = malloc(size);
|
||||
|
||||
cgltf_size written = cgltf_write(&options, buf, size, data);
|
||||
if (written != size)
|
||||
{
|
||||
/* TODO handle error */
|
||||
}
|
||||
```
|
||||
|
||||
Note that cgltf does not write the contents of extra files such as buffers or images. You'll need to write this data yourself.
|
||||
|
||||
**For more in-depth documentation and a description of the public interface refer to the top of the `cgltf_write.h` file.**
|
||||
|
||||
|
||||
## Features
|
||||
cgltf supports core glTF 2.0:
|
||||
- glb (binary files) and gltf (JSON files)
|
||||
- meshes (including accessors, buffer views, buffers)
|
||||
- materials (including textures, samplers, images)
|
||||
- scenes and nodes
|
||||
- skins
|
||||
- animations
|
||||
- cameras
|
||||
- morph targets
|
||||
- extras data
|
||||
|
||||
cgltf also supports some glTF extensions:
|
||||
- EXT_mesh_gpu_instancing
|
||||
- EXT_meshopt_compression
|
||||
- KHR_draco_mesh_compression (requires a library like [Google's Draco](https://github.com/google/draco) for decompression though)
|
||||
- KHR_lights_punctual
|
||||
- KHR_materials_clearcoat
|
||||
- KHR_materials_emissive_strength
|
||||
- KHR_materials_ior
|
||||
- KHR_materials_iridescence
|
||||
- KHR_materials_pbrSpecularGlossiness
|
||||
- KHR_materials_sheen
|
||||
- KHR_materials_specular
|
||||
- KHR_materials_transmission
|
||||
- KHR_materials_unlit
|
||||
- KHR_materials_variants
|
||||
- KHR_materials_volume
|
||||
- KHR_texture_basisu (requires a library like [Binomial Basisu](https://github.com/BinomialLLC/basis_universal) for transcoding to native compressed texture)
|
||||
- KHR_texture_transform
|
||||
|
||||
cgltf does **not** yet support unlisted extensions. However, unlisted extensions can be accessed via "extensions" member on objects.
|
||||
|
||||
## Building
|
||||
The easiest approach is to integrate the `cgltf.h` header file into your project. If you are unfamiliar with single-file C libraries (also known as stb-style libraries), this is how it goes:
|
||||
|
||||
1. Include `cgltf.h` where you need the functionality.
|
||||
1. Have exactly one source file that defines `CGLTF_IMPLEMENTATION` before including `cgltf.h`.
|
||||
1. Use the cgltf functions as described above.
|
||||
|
||||
Support for writing can be found in a separate file called `cgltf_write.h` (which includes `cgltf.h`). Building it works analogously using the `CGLTF_WRITE_IMPLEMENTATION` define.
|
||||
|
||||
## Contributing
|
||||
Everyone is welcome to contribute to the library. If you find any problems, you can submit them using [GitHub's issue system](https://github.com/jkuhlmann/cgltf/issues). If you want to contribute code, you should fork the project and then send a pull request.
|
||||
|
||||
|
||||
## Dependencies
|
||||
None.
|
||||
|
||||
C headers being used by the implementation:
|
||||
```
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
#include <assert.h> // If asserts are enabled.
|
||||
```
|
||||
|
||||
Note, this library has a copy of the [JSMN JSON parser](https://github.com/zserge/jsmn) embedded in its source.
|
||||
|
||||
## Testing
|
||||
There is a Python script in the `test/` folder that retrieves the glTF 2.0 sample files from the glTF-Sample-Models repository (https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0) and runs the library against all gltf and glb files.
|
||||
|
||||
Here's one way to build and run the test:
|
||||
|
||||
cd test ; mkdir build ; cd build ; cmake .. -DCMAKE_BUILD_TYPE=Debug
|
||||
make -j
|
||||
cd ..
|
||||
./test_all.py
|
||||
|
||||
There is also a llvm-fuzz test in `fuzz/`. See http://llvm.org/docs/LibFuzzer.html for more information.
|
||||
6739
source/thirdparty/cgltf/cgltf.h
vendored
6739
source/thirdparty/cgltf/cgltf.h
vendored
File diff suppressed because it is too large
Load Diff
1403
source/thirdparty/cgltf/cgltf_write.h
vendored
1403
source/thirdparty/cgltf/cgltf_write.h
vendored
File diff suppressed because it is too large
Load Diff
1107
source/thirdparty/imgui/GraphEditor.cpp
vendored
1107
source/thirdparty/imgui/GraphEditor.cpp
vendored
File diff suppressed because it is too large
Load Diff
151
source/thirdparty/imgui/GraphEditor.h
vendored
151
source/thirdparty/imgui/GraphEditor.h
vendored
@@ -1,151 +0,0 @@
|
||||
// https://github.com/CedricGuillemet/ImGuizmo
|
||||
// v 1.89 WIP
|
||||
//
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) 2021 Cedric Guillemet
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files(the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions :
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <stdint.h>
|
||||
#include <string>
|
||||
#include "imgui.h"
|
||||
#include "imgui_internal.h"
|
||||
|
||||
namespace GraphEditor {
|
||||
|
||||
typedef size_t NodeIndex;
|
||||
typedef size_t SlotIndex;
|
||||
typedef size_t LinkIndex;
|
||||
typedef size_t TemplateIndex;
|
||||
|
||||
// Force the view to be respositionned and zoom to fit nodes with Show function.
|
||||
// Parameter value will be changed to Fit_None by the function.
|
||||
enum FitOnScreen
|
||||
{
|
||||
Fit_None,
|
||||
Fit_AllNodes,
|
||||
Fit_SelectedNodes
|
||||
};
|
||||
|
||||
// Display options and colors
|
||||
struct Options
|
||||
{
|
||||
ImRect mMinimap{{0.75f, 0.8f, 0.99f, 0.99f}}; // rectangle coordinates of minimap
|
||||
ImU32 mBackgroundColor{ IM_COL32(40, 40, 40, 255) }; // full background color
|
||||
ImU32 mGridColor{ IM_COL32(0, 0, 0, 60) }; // grid lines color
|
||||
ImU32 mGridColor2{ IM_COL32(0, 0, 0, 160) }; // grid lines color every 10th
|
||||
ImU32 mSelectedNodeBorderColor{ IM_COL32(255, 130, 30, 255) }; // node border color when it's selected
|
||||
ImU32 mNodeBorderColor{ IM_COL32(100, 100, 100, 0) }; // node border color when it's not selected
|
||||
ImU32 mQuadSelection{ IM_COL32(255, 32, 32, 64) }; // quad selection inside color
|
||||
ImU32 mQuadSelectionBorder{ IM_COL32(255, 32, 32, 255) }; // quad selection border color
|
||||
ImU32 mDefaultSlotColor{ IM_COL32(128, 128, 128, 255) }; // when no color is provided in node template, use this value
|
||||
ImU32 mFrameFocus{ IM_COL32(64, 128, 255, 255) }; // rectangle border when graph editor has focus
|
||||
float mLineThickness{ 5 }; // links width in pixels when zoom value is 1
|
||||
float mGridSize{ 64.f }; // background grid size in pixels when zoom value is 1
|
||||
float mRounding{ 3.f }; // rounding at node corners
|
||||
float mZoomRatio{ 0.1f }; // factor per mouse wheel delta
|
||||
float mZoomLerpFactor{ 0.25f }; // the smaller, the smoother
|
||||
float mBorderSelectionThickness{ 6.f }; // thickness of selection border around nodes
|
||||
float mBorderThickness{ 6.f }; // thickness of selection border around nodes
|
||||
float mNodeSlotRadius{ 8.f }; // circle radius for inputs and outputs
|
||||
float mNodeSlotHoverFactor{ 1.2f }; // increase size when hovering
|
||||
float mMinZoom{ 0.2f }, mMaxZoom { 1.1f };
|
||||
float mSnap{ 5.f };
|
||||
bool mDisplayLinksAsCurves{ true }; // false is straight and 45deg lines
|
||||
bool mAllowQuadSelection{ true }; // multiple selection using drag and drop
|
||||
bool mRenderGrid{ true }; // grid or nothing
|
||||
bool mDrawIONameOnHover{ true }; // only draw node input/output when hovering
|
||||
};
|
||||
|
||||
// View state: scroll position and zoom factor
|
||||
struct ViewState
|
||||
{
|
||||
ImVec2 mPosition{0.0f, 0.0f}; // scroll position
|
||||
float mFactor{ 1.0f }; // current zoom factor
|
||||
float mFactorTarget{ 1.0f }; // targeted zoom factor interpolated using Options.mZoomLerpFactor
|
||||
};
|
||||
|
||||
struct Template
|
||||
{
|
||||
ImU32 mHeaderColor;
|
||||
ImU32 mBackgroundColor;
|
||||
ImU32 mBackgroundColorOver;
|
||||
ImU8 mInputCount;
|
||||
const char** mInputNames; // can be nullptr. No text displayed.
|
||||
ImU32* mInputColors; // can be nullptr, default slot color will be used.
|
||||
ImU8 mOutputCount;
|
||||
const char** mOutputNames; // can be nullptr. No text displayed.
|
||||
ImU32* mOutputColors; // can be nullptr, default slot color will be used.
|
||||
};
|
||||
|
||||
struct Node
|
||||
{
|
||||
const char* mName;
|
||||
TemplateIndex mTemplateIndex;
|
||||
ImRect mRect;
|
||||
bool mSelected{ false };
|
||||
};
|
||||
|
||||
struct Link
|
||||
{
|
||||
NodeIndex mInputNodeIndex;
|
||||
SlotIndex mInputSlotIndex;
|
||||
NodeIndex mOutputNodeIndex;
|
||||
SlotIndex mOutputSlotIndex;
|
||||
};
|
||||
|
||||
struct Delegate
|
||||
{
|
||||
virtual bool AllowedLink(NodeIndex from, NodeIndex to) = 0;
|
||||
|
||||
virtual void SelectNode(NodeIndex nodeIndex, bool selected) = 0;
|
||||
virtual void MoveSelectedNodes(const ImVec2 delta) = 0;
|
||||
|
||||
virtual void AddLink(NodeIndex inputNodeIndex, SlotIndex inputSlotIndex, NodeIndex outputNodeIndex, SlotIndex outputSlotIndex) = 0;
|
||||
virtual void DelLink(LinkIndex linkIndex) = 0;
|
||||
|
||||
// user is responsible for clipping
|
||||
virtual void CustomDraw(ImDrawList* drawList, ImRect rectangle, NodeIndex nodeIndex) = 0;
|
||||
|
||||
// use mouse position to open context menu
|
||||
// if nodeIndex != -1, right click happens on the specified node
|
||||
virtual void RightClick(NodeIndex nodeIndex, SlotIndex slotIndexInput, SlotIndex slotIndexOutput) = 0;
|
||||
|
||||
virtual const size_t GetTemplateCount() = 0;
|
||||
virtual const Template GetTemplate(TemplateIndex index) = 0;
|
||||
|
||||
virtual const size_t GetNodeCount() = 0;
|
||||
virtual const Node GetNode(NodeIndex index) = 0;
|
||||
|
||||
virtual const size_t GetLinkCount() = 0;
|
||||
virtual const Link GetLink(LinkIndex index) = 0;
|
||||
|
||||
virtual ~Delegate() = default;
|
||||
};
|
||||
|
||||
void Show(Delegate& delegate, const Options& options, ViewState& viewState, bool enabled, FitOnScreen* fit = nullptr);
|
||||
void GraphEditorClear();
|
||||
|
||||
bool EditOptions(Options& options);
|
||||
|
||||
} // namespace
|
||||
457
source/thirdparty/imgui/ImCurveEdit.cpp
vendored
457
source/thirdparty/imgui/ImCurveEdit.cpp
vendored
@@ -1,457 +0,0 @@
|
||||
// https://github.com/CedricGuillemet/ImGuizmo
|
||||
// v 1.89 WIP
|
||||
//
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) 2021 Cedric Guillemet
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files(the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions :
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
#include "ImCurveEdit.h"
|
||||
#include "imgui.h"
|
||||
#include "imgui_internal.h"
|
||||
#include <stdint.h>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
#if defined(_MSC_VER) || defined(__MINGW32__)
|
||||
#include <malloc.h>
|
||||
#endif
|
||||
#if !defined(_MSC_VER) && !defined(__MINGW64_VERSION_MAJOR)
|
||||
#define _malloca(x) alloca(x)
|
||||
#define _freea(x)
|
||||
#endif
|
||||
|
||||
namespace ImCurveEdit
|
||||
{
|
||||
|
||||
#ifndef IMGUI_DEFINE_MATH_OPERATORS
|
||||
static ImVec2 operator+(const ImVec2& a, const ImVec2& b) {
|
||||
return ImVec2(a.x + b.x, a.y + b.y);
|
||||
}
|
||||
|
||||
static ImVec2 operator-(const ImVec2& a, const ImVec2& b) {
|
||||
return ImVec2(a.x - b.x, a.y - b.y);
|
||||
}
|
||||
|
||||
static ImVec2 operator*(const ImVec2& a, const ImVec2& b) {
|
||||
return ImVec2(a.x * b.x, a.y * b.y);
|
||||
}
|
||||
|
||||
static ImVec2 operator/(const ImVec2& a, const ImVec2& b) {
|
||||
return ImVec2(a.x / b.x, a.y / b.y);
|
||||
}
|
||||
|
||||
static ImVec2 operator*(const ImVec2& a, const float b) {
|
||||
return ImVec2(a.x * b, a.y * b);
|
||||
}
|
||||
#endif
|
||||
|
||||
static float smoothstep(float edge0, float edge1, float x)
|
||||
{
|
||||
x = ImClamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);
|
||||
return x * x * (3 - 2 * x);
|
||||
}
|
||||
|
||||
static float distance(float x, float y, float x1, float y1, float x2, float y2)
|
||||
{
|
||||
float A = x - x1;
|
||||
float B = y - y1;
|
||||
float C = x2 - x1;
|
||||
float D = y2 - y1;
|
||||
|
||||
float dot = A * C + B * D;
|
||||
float len_sq = C * C + D * D;
|
||||
float param = -1.f;
|
||||
if (len_sq > FLT_EPSILON)
|
||||
param = dot / len_sq;
|
||||
|
||||
float xx, yy;
|
||||
|
||||
if (param < 0.f) {
|
||||
xx = x1;
|
||||
yy = y1;
|
||||
}
|
||||
else if (param > 1.f) {
|
||||
xx = x2;
|
||||
yy = y2;
|
||||
}
|
||||
else {
|
||||
xx = x1 + param * C;
|
||||
yy = y1 + param * D;
|
||||
}
|
||||
|
||||
float dx = x - xx;
|
||||
float dy = y - yy;
|
||||
return sqrtf(dx * dx + dy * dy);
|
||||
}
|
||||
|
||||
static int DrawPoint(ImDrawList* draw_list, ImVec2 pos, const ImVec2 size, const ImVec2 offset, bool edited)
|
||||
{
|
||||
int ret = 0;
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
static const ImVec2 localOffsets[4] = { ImVec2(1,0), ImVec2(0,1), ImVec2(-1,0), ImVec2(0,-1) };
|
||||
ImVec2 offsets[4];
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
offsets[i] = pos * size + localOffsets[i] * 4.5f + offset;
|
||||
}
|
||||
|
||||
const ImVec2 center = pos * size + offset;
|
||||
const ImRect anchor(center - ImVec2(5, 5), center + ImVec2(5, 5));
|
||||
draw_list->AddConvexPolyFilled(offsets, 4, 0xFF000000);
|
||||
if (anchor.Contains(io.MousePos))
|
||||
{
|
||||
ret = 1;
|
||||
if (io.MouseDown[0])
|
||||
ret = 2;
|
||||
}
|
||||
if (edited)
|
||||
draw_list->AddPolyline(offsets, 4, 0xFFFFFFFF, true, 3.0f);
|
||||
else if (ret)
|
||||
draw_list->AddPolyline(offsets, 4, 0xFF80B0FF, true, 2.0f);
|
||||
else
|
||||
draw_list->AddPolyline(offsets, 4, 0xFF0080FF, true, 2.0f);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
int Edit(Delegate& delegate, const ImVec2& size, unsigned int id, const ImRect* clippingRect, ImVector<EditPoint>* selectedPoints)
|
||||
{
|
||||
static bool selectingQuad = false;
|
||||
static ImVec2 quadSelection;
|
||||
static int overCurve = -1;
|
||||
static int movingCurve = -1;
|
||||
static bool scrollingV = false;
|
||||
static std::set<EditPoint> selection;
|
||||
static bool overSelectedPoint = false;
|
||||
|
||||
int ret = 0;
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
|
||||
ImGui::PushStyleColor(ImGuiCol_Border, 0);
|
||||
ImGui::BeginChildFrame(id, size);
|
||||
delegate.focused = ImGui::IsWindowFocused();
|
||||
ImDrawList* draw_list = ImGui::GetWindowDrawList();
|
||||
if (clippingRect)
|
||||
draw_list->PushClipRect(clippingRect->Min, clippingRect->Max, true);
|
||||
|
||||
const ImVec2 offset = ImGui::GetCursorScreenPos() + ImVec2(0.f, size.y);
|
||||
const ImVec2 ssize(size.x, -size.y);
|
||||
const ImRect container(offset + ImVec2(0.f, ssize.y), offset + ImVec2(ssize.x, 0.f));
|
||||
ImVec2& min = delegate.GetMin();
|
||||
ImVec2& max = delegate.GetMax();
|
||||
|
||||
// handle zoom and VScroll
|
||||
if (container.Contains(io.MousePos))
|
||||
{
|
||||
if (fabsf(io.MouseWheel) > FLT_EPSILON)
|
||||
{
|
||||
const float r = (io.MousePos.y - offset.y) / ssize.y;
|
||||
float ratioY = ImLerp(min.y, max.y, r);
|
||||
auto scaleValue = [&](float v) {
|
||||
v -= ratioY;
|
||||
v *= (1.f - io.MouseWheel * 0.05f);
|
||||
v += ratioY;
|
||||
return v;
|
||||
};
|
||||
min.y = scaleValue(min.y);
|
||||
max.y = scaleValue(max.y);
|
||||
}
|
||||
if (!scrollingV && ImGui::IsMouseDown(2))
|
||||
{
|
||||
scrollingV = true;
|
||||
}
|
||||
}
|
||||
ImVec2 range = max - min + ImVec2(1.f, 0.f); // +1 because of inclusive last frame
|
||||
|
||||
const ImVec2 viewSize(size.x, -size.y);
|
||||
const ImVec2 sizeOfPixel = ImVec2(1.f, 1.f) / viewSize;
|
||||
const size_t curveCount = delegate.GetCurveCount();
|
||||
|
||||
if (scrollingV)
|
||||
{
|
||||
float deltaH = io.MouseDelta.y * range.y * sizeOfPixel.y;
|
||||
min.y -= deltaH;
|
||||
max.y -= deltaH;
|
||||
if (!ImGui::IsMouseDown(2))
|
||||
scrollingV = false;
|
||||
}
|
||||
|
||||
draw_list->AddRectFilled(offset, offset + ssize, delegate.GetBackgroundColor());
|
||||
|
||||
auto pointToRange = [&](ImVec2 pt) { return (pt - min) / range; };
|
||||
auto rangeToPoint = [&](ImVec2 pt) { return (pt * range) + min; };
|
||||
|
||||
draw_list->AddLine(ImVec2(-1.f, -min.y / range.y) * viewSize + offset, ImVec2(1.f, -min.y / range.y) * viewSize + offset, 0xFF000000, 1.5f);
|
||||
bool overCurveOrPoint = false;
|
||||
|
||||
int localOverCurve = -1;
|
||||
// make sure highlighted curve is rendered last
|
||||
int* curvesIndex = (int*)_malloca(sizeof(int) * curveCount);
|
||||
for (size_t c = 0; c < curveCount; c++)
|
||||
curvesIndex[c] = int(c);
|
||||
int highLightedCurveIndex = -1;
|
||||
if (overCurve != -1 && curveCount)
|
||||
{
|
||||
ImSwap(curvesIndex[overCurve], curvesIndex[curveCount - 1]);
|
||||
highLightedCurveIndex = overCurve;
|
||||
}
|
||||
|
||||
for (size_t cur = 0; cur < curveCount; cur++)
|
||||
{
|
||||
int c = curvesIndex[cur];
|
||||
if (!delegate.IsVisible(c))
|
||||
continue;
|
||||
const size_t ptCount = delegate.GetPointCount(c);
|
||||
if (ptCount < 1)
|
||||
continue;
|
||||
CurveType curveType = delegate.GetCurveType(c);
|
||||
if (curveType == CurveNone)
|
||||
continue;
|
||||
const ImVec2* pts = delegate.GetPoints(c);
|
||||
uint32_t curveColor = delegate.GetCurveColor(c);
|
||||
if ((c == highLightedCurveIndex && selection.empty() && !selectingQuad) || movingCurve == c)
|
||||
curveColor = 0xFFFFFFFF;
|
||||
|
||||
for (size_t p = 0; p < ptCount - 1; p++)
|
||||
{
|
||||
const ImVec2 p1 = pointToRange(pts[p]);
|
||||
const ImVec2 p2 = pointToRange(pts[p + 1]);
|
||||
|
||||
if (curveType == CurveSmooth || curveType == CurveLinear)
|
||||
{
|
||||
size_t subStepCount = (curveType == CurveSmooth) ? 20 : 2;
|
||||
float step = 1.f / float(subStepCount - 1);
|
||||
for (size_t substep = 0; substep < subStepCount - 1; substep++)
|
||||
{
|
||||
float t = float(substep) * step;
|
||||
|
||||
const ImVec2 sp1 = ImLerp(p1, p2, t);
|
||||
const ImVec2 sp2 = ImLerp(p1, p2, t + step);
|
||||
|
||||
const float rt1 = smoothstep(p1.x, p2.x, sp1.x);
|
||||
const float rt2 = smoothstep(p1.x, p2.x, sp2.x);
|
||||
|
||||
const ImVec2 pos1 = ImVec2(sp1.x, ImLerp(p1.y, p2.y, rt1)) * viewSize + offset;
|
||||
const ImVec2 pos2 = ImVec2(sp2.x, ImLerp(p1.y, p2.y, rt2)) * viewSize + offset;
|
||||
|
||||
if (distance(io.MousePos.x, io.MousePos.y, pos1.x, pos1.y, pos2.x, pos2.y) < 8.f && !scrollingV)
|
||||
{
|
||||
localOverCurve = int(c);
|
||||
overCurve = int(c);
|
||||
overCurveOrPoint = true;
|
||||
}
|
||||
|
||||
draw_list->AddLine(pos1, pos2, curveColor, 1.3f);
|
||||
} // substep
|
||||
}
|
||||
else if (curveType == CurveDiscrete)
|
||||
{
|
||||
ImVec2 dp1 = p1 * viewSize + offset;
|
||||
ImVec2 dp2 = ImVec2(p2.x, p1.y) * viewSize + offset;
|
||||
ImVec2 dp3 = p2 * viewSize + offset;
|
||||
draw_list->AddLine(dp1, dp2, curveColor, 1.3f);
|
||||
draw_list->AddLine(dp2, dp3, curveColor, 1.3f);
|
||||
|
||||
if ((distance(io.MousePos.x, io.MousePos.y, dp1.x, dp1.y, dp3.x, dp1.y) < 8.f ||
|
||||
distance(io.MousePos.x, io.MousePos.y, dp3.x, dp1.y, dp3.x, dp3.y) < 8.f)
|
||||
/*&& localOverCurve == -1*/)
|
||||
{
|
||||
localOverCurve = int(c);
|
||||
overCurve = int(c);
|
||||
overCurveOrPoint = true;
|
||||
}
|
||||
}
|
||||
} // point loop
|
||||
|
||||
for (size_t p = 0; p < ptCount; p++)
|
||||
{
|
||||
const int drawState = DrawPoint(draw_list, pointToRange(pts[p]), viewSize, offset, (selection.find({ int(c), int(p) }) != selection.end() && movingCurve == -1 && !scrollingV));
|
||||
if (drawState && movingCurve == -1 && !selectingQuad)
|
||||
{
|
||||
overCurveOrPoint = true;
|
||||
overSelectedPoint = true;
|
||||
overCurve = -1;
|
||||
if (drawState == 2)
|
||||
{
|
||||
if (!io.KeyShift && selection.find({ int(c), int(p) }) == selection.end())
|
||||
selection.clear();
|
||||
selection.insert({ int(c), int(p) });
|
||||
}
|
||||
}
|
||||
}
|
||||
} // curves loop
|
||||
|
||||
if (localOverCurve == -1)
|
||||
overCurve = -1;
|
||||
|
||||
// move selection
|
||||
static bool pointsMoved = false;
|
||||
static ImVec2 mousePosOrigin;
|
||||
static std::vector<ImVec2> originalPoints;
|
||||
if (overSelectedPoint && io.MouseDown[0])
|
||||
{
|
||||
if ((fabsf(io.MouseDelta.x) > 0.f || fabsf(io.MouseDelta.y) > 0.f) && !selection.empty())
|
||||
{
|
||||
if (!pointsMoved)
|
||||
{
|
||||
delegate.BeginEdit(0);
|
||||
mousePosOrigin = io.MousePos;
|
||||
originalPoints.resize(selection.size());
|
||||
int index = 0;
|
||||
for (auto& sel : selection)
|
||||
{
|
||||
const ImVec2* pts = delegate.GetPoints(sel.curveIndex);
|
||||
originalPoints[index++] = pts[sel.pointIndex];
|
||||
}
|
||||
}
|
||||
pointsMoved = true;
|
||||
ret = 1;
|
||||
auto prevSelection = selection;
|
||||
int originalIndex = 0;
|
||||
for (auto& sel : prevSelection)
|
||||
{
|
||||
const ImVec2 p = rangeToPoint(pointToRange(originalPoints[originalIndex]) + (io.MousePos - mousePosOrigin) * sizeOfPixel);
|
||||
const int newIndex = delegate.EditPoint(sel.curveIndex, sel.pointIndex, p);
|
||||
if (newIndex != sel.pointIndex)
|
||||
{
|
||||
selection.erase(sel);
|
||||
selection.insert({ sel.curveIndex, newIndex });
|
||||
}
|
||||
originalIndex++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (overSelectedPoint && !io.MouseDown[0])
|
||||
{
|
||||
overSelectedPoint = false;
|
||||
if (pointsMoved)
|
||||
{
|
||||
pointsMoved = false;
|
||||
delegate.EndEdit();
|
||||
}
|
||||
}
|
||||
|
||||
// add point
|
||||
if (overCurve != -1 && io.MouseDoubleClicked[0])
|
||||
{
|
||||
const ImVec2 np = rangeToPoint((io.MousePos - offset) / viewSize);
|
||||
delegate.BeginEdit(overCurve);
|
||||
delegate.AddPoint(overCurve, np);
|
||||
delegate.EndEdit();
|
||||
ret = 1;
|
||||
}
|
||||
|
||||
// move curve
|
||||
|
||||
if (movingCurve != -1)
|
||||
{
|
||||
const size_t ptCount = delegate.GetPointCount(movingCurve);
|
||||
const ImVec2* pts = delegate.GetPoints(movingCurve);
|
||||
if (!pointsMoved)
|
||||
{
|
||||
mousePosOrigin = io.MousePos;
|
||||
pointsMoved = true;
|
||||
originalPoints.resize(ptCount);
|
||||
for (size_t index = 0; index < ptCount; index++)
|
||||
{
|
||||
originalPoints[index] = pts[index];
|
||||
}
|
||||
}
|
||||
if (ptCount >= 1)
|
||||
{
|
||||
for (size_t p = 0; p < ptCount; p++)
|
||||
{
|
||||
delegate.EditPoint(movingCurve, int(p), rangeToPoint(pointToRange(originalPoints[p]) + (io.MousePos - mousePosOrigin) * sizeOfPixel));
|
||||
}
|
||||
ret = 1;
|
||||
}
|
||||
if (!io.MouseDown[0])
|
||||
{
|
||||
movingCurve = -1;
|
||||
pointsMoved = false;
|
||||
delegate.EndEdit();
|
||||
}
|
||||
}
|
||||
if (movingCurve == -1 && overCurve != -1 && ImGui::IsMouseClicked(0) && selection.empty() && !selectingQuad)
|
||||
{
|
||||
movingCurve = overCurve;
|
||||
delegate.BeginEdit(overCurve);
|
||||
}
|
||||
|
||||
// quad selection
|
||||
if (selectingQuad)
|
||||
{
|
||||
const ImVec2 bmin = ImMin(quadSelection, io.MousePos);
|
||||
const ImVec2 bmax = ImMax(quadSelection, io.MousePos);
|
||||
draw_list->AddRectFilled(bmin, bmax, 0x40FF0000, 1.f);
|
||||
draw_list->AddRect(bmin, bmax, 0xFFFF0000, 1.f);
|
||||
const ImRect selectionQuad(bmin, bmax);
|
||||
if (!io.MouseDown[0])
|
||||
{
|
||||
if (!io.KeyShift)
|
||||
selection.clear();
|
||||
// select everythnig is quad
|
||||
for (size_t c = 0; c < curveCount; c++)
|
||||
{
|
||||
if (!delegate.IsVisible(c))
|
||||
continue;
|
||||
|
||||
const size_t ptCount = delegate.GetPointCount(c);
|
||||
if (ptCount < 1)
|
||||
continue;
|
||||
|
||||
const ImVec2* pts = delegate.GetPoints(c);
|
||||
for (size_t p = 0; p < ptCount; p++)
|
||||
{
|
||||
const ImVec2 center = pointToRange(pts[p]) * viewSize + offset;
|
||||
if (selectionQuad.Contains(center))
|
||||
selection.insert({ int(c), int(p) });
|
||||
}
|
||||
}
|
||||
// done
|
||||
selectingQuad = false;
|
||||
}
|
||||
}
|
||||
if (!overCurveOrPoint && ImGui::IsMouseClicked(0) && !selectingQuad && movingCurve == -1 && !overSelectedPoint && container.Contains(io.MousePos))
|
||||
{
|
||||
selectingQuad = true;
|
||||
quadSelection = io.MousePos;
|
||||
}
|
||||
if (clippingRect)
|
||||
draw_list->PopClipRect();
|
||||
|
||||
ImGui::EndChildFrame();
|
||||
ImGui::PopStyleVar();
|
||||
ImGui::PopStyleColor(1);
|
||||
|
||||
if (selectedPoints)
|
||||
{
|
||||
selectedPoints->resize(int(selection.size()));
|
||||
int index = 0;
|
||||
for (auto& point : selection)
|
||||
(*selectedPoints)[index++] = point;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
82
source/thirdparty/imgui/ImCurveEdit.h
vendored
82
source/thirdparty/imgui/ImCurveEdit.h
vendored
@@ -1,82 +0,0 @@
|
||||
// https://github.com/CedricGuillemet/ImGuizmo
|
||||
// v 1.89 WIP
|
||||
//
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) 2021 Cedric Guillemet
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files(the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions :
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include "imgui.h"
|
||||
|
||||
struct ImRect;
|
||||
|
||||
namespace ImCurveEdit
|
||||
{
|
||||
enum CurveType
|
||||
{
|
||||
CurveNone,
|
||||
CurveDiscrete,
|
||||
CurveLinear,
|
||||
CurveSmooth,
|
||||
CurveBezier,
|
||||
};
|
||||
|
||||
struct EditPoint
|
||||
{
|
||||
int curveIndex;
|
||||
int pointIndex;
|
||||
bool operator <(const EditPoint& other) const
|
||||
{
|
||||
if (curveIndex < other.curveIndex)
|
||||
return true;
|
||||
if (curveIndex > other.curveIndex)
|
||||
return false;
|
||||
|
||||
if (pointIndex < other.pointIndex)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
struct Delegate
|
||||
{
|
||||
bool focused = false;
|
||||
virtual size_t GetCurveCount() = 0;
|
||||
virtual bool IsVisible(size_t /*curveIndex*/) { return true; }
|
||||
virtual CurveType GetCurveType(size_t /*curveIndex*/) const { return CurveLinear; }
|
||||
virtual ImVec2& GetMin() = 0;
|
||||
virtual ImVec2& GetMax() = 0;
|
||||
virtual size_t GetPointCount(size_t curveIndex) = 0;
|
||||
virtual uint32_t GetCurveColor(size_t curveIndex) = 0;
|
||||
virtual ImVec2* GetPoints(size_t curveIndex) = 0;
|
||||
virtual int EditPoint(size_t curveIndex, int pointIndex, ImVec2 value) = 0;
|
||||
virtual void AddPoint(size_t curveIndex, ImVec2 value) = 0;
|
||||
virtual unsigned int GetBackgroundColor() { return 0xFF202020; }
|
||||
// handle undo/redo thru this functions
|
||||
virtual void BeginEdit(int /*index*/) {}
|
||||
virtual void EndEdit() {}
|
||||
|
||||
virtual ~Delegate() = default;
|
||||
};
|
||||
|
||||
int Edit(Delegate& delegate, const ImVec2& size, unsigned int id, const ImRect* clippingRect = NULL, ImVector<EditPoint>* selectedPoints = NULL);
|
||||
}
|
||||
116
source/thirdparty/imgui/ImGradient.cpp
vendored
116
source/thirdparty/imgui/ImGradient.cpp
vendored
@@ -1,116 +0,0 @@
|
||||
// https://github.com/CedricGuillemet/ImGuizmo
|
||||
// v 1.89 WIP
|
||||
//
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) 2021 Cedric Guillemet
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files(the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions :
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
#include "ImGradient.h"
|
||||
#include "imgui.h"
|
||||
#include "imgui_internal.h"
|
||||
|
||||
namespace ImGradient
|
||||
{
|
||||
#ifndef IMGUI_DEFINE_MATH_OPERATORS
|
||||
static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); }
|
||||
static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); }
|
||||
static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); }
|
||||
static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }
|
||||
static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
|
||||
static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); }
|
||||
#endif
|
||||
|
||||
static int DrawPoint(ImDrawList* draw_list, ImVec4 color, const ImVec2 size, bool editing, ImVec2 pos)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
ImVec2 p1 = ImLerp(pos, ImVec2(pos + ImVec2(size.x - size.y, 0.f)), color.w) + ImVec2(3, 3);
|
||||
ImVec2 p2 = ImLerp(pos + ImVec2(size.y, size.y), ImVec2(pos + size), color.w) - ImVec2(3, 3);
|
||||
ImRect rc(p1, p2);
|
||||
|
||||
color.w = 1.f;
|
||||
draw_list->AddRectFilled(p1, p2, ImColor(color));
|
||||
if (editing)
|
||||
draw_list->AddRect(p1, p2, 0xFFFFFFFF, 2.f, 15, 2.5f);
|
||||
else
|
||||
draw_list->AddRect(p1, p2, 0x80FFFFFF, 2.f, 15, 1.25f);
|
||||
|
||||
if (rc.Contains(io.MousePos))
|
||||
{
|
||||
if (io.MouseClicked[0])
|
||||
return 2;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool Edit(Delegate& delegate, const ImVec2& size, int& selection)
|
||||
{
|
||||
bool ret = false;
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
|
||||
ImGui::BeginChildFrame(137, size);
|
||||
|
||||
ImDrawList* draw_list = ImGui::GetWindowDrawList();
|
||||
const ImVec2 offset = ImGui::GetCursorScreenPos();
|
||||
|
||||
const ImVec4* pts = delegate.GetPoints();
|
||||
static int currentSelection = -1;
|
||||
static int movingPt = -1;
|
||||
if (currentSelection >= int(delegate.GetPointCount()))
|
||||
currentSelection = -1;
|
||||
if (movingPt != -1)
|
||||
{
|
||||
ImVec4 current = pts[movingPt];
|
||||
current.w += io.MouseDelta.x / size.x;
|
||||
current.w = ImClamp(current.w, 0.f, 1.f);
|
||||
delegate.EditPoint(movingPt, current);
|
||||
ret = true;
|
||||
if (!io.MouseDown[0])
|
||||
movingPt = -1;
|
||||
}
|
||||
for (size_t i = 0; i < delegate.GetPointCount(); i++)
|
||||
{
|
||||
int ptSel = DrawPoint(draw_list, pts[i], size, i == currentSelection, offset);
|
||||
if (ptSel == 2)
|
||||
{
|
||||
currentSelection = int(i);
|
||||
ret = true;
|
||||
}
|
||||
if (ptSel == 1 && io.MouseDown[0] && movingPt == -1)
|
||||
{
|
||||
movingPt = int(i);
|
||||
}
|
||||
}
|
||||
ImRect rc(offset, offset + size);
|
||||
if (rc.Contains(io.MousePos) && io.MouseDoubleClicked[0])
|
||||
{
|
||||
float t = (io.MousePos.x - offset.x) / size.x;
|
||||
delegate.AddPoint(delegate.GetPoint(t));
|
||||
ret = true;
|
||||
}
|
||||
ImGui::EndChildFrame();
|
||||
ImGui::PopStyleVar();
|
||||
|
||||
selection = currentSelection;
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
45
source/thirdparty/imgui/ImGradient.h
vendored
45
source/thirdparty/imgui/ImGradient.h
vendored
@@ -1,45 +0,0 @@
|
||||
// https://github.com/CedricGuillemet/ImGuizmo
|
||||
// v 1.89 WIP
|
||||
//
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) 2021 Cedric Guillemet
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files(the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions :
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
|
||||
struct ImVec4;
|
||||
struct ImVec2;
|
||||
|
||||
namespace ImGradient
|
||||
{
|
||||
struct Delegate
|
||||
{
|
||||
virtual size_t GetPointCount() = 0;
|
||||
virtual ImVec4* GetPoints() = 0;
|
||||
virtual int EditPoint(int pointIndex, ImVec4 value) = 0;
|
||||
virtual ImVec4 GetPoint(float t) = 0;
|
||||
virtual void AddPoint(ImVec4 value) = 0;
|
||||
virtual ~Delegate() = default;
|
||||
};
|
||||
|
||||
bool Edit(Delegate& delegate, const ImVec2& size, int& selection);
|
||||
}
|
||||
2996
source/thirdparty/imgui/ImGuizmo.cpp
vendored
2996
source/thirdparty/imgui/ImGuizmo.cpp
vendored
File diff suppressed because it is too large
Load Diff
272
source/thirdparty/imgui/ImGuizmo.h
vendored
272
source/thirdparty/imgui/ImGuizmo.h
vendored
@@ -1,272 +0,0 @@
|
||||
// https://github.com/CedricGuillemet/ImGuizmo
|
||||
// v 1.89 WIP
|
||||
//
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) 2021 Cedric Guillemet
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files(the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions :
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// History :
|
||||
// 2019/11/03 View gizmo
|
||||
// 2016/09/11 Behind camera culling. Scaling Delta matrix not multiplied by source matrix scales. local/world rotation and translation fixed. Display message is incorrect (X: ... Y:...) in local mode.
|
||||
// 2016/09/09 Hatched negative axis. Snapping. Documentation update.
|
||||
// 2016/09/04 Axis switch and translation plan autohiding. Scale transform stability improved
|
||||
// 2016/09/01 Mogwai changed to Manipulate. Draw debug cube. Fixed inverted scale. Mixing scale and translation/rotation gives bad results.
|
||||
// 2016/08/31 First version
|
||||
//
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// Future (no order):
|
||||
//
|
||||
// - Multi view
|
||||
// - display rotation/translation/scale infos in local/world space and not only local
|
||||
// - finish local/world matrix application
|
||||
// - OPERATION as bitmask
|
||||
//
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// Example
|
||||
#if 0
|
||||
void EditTransform(const Camera& camera, matrix_t& matrix)
|
||||
{
|
||||
static ImGuizmo::OPERATION mCurrentGizmoOperation(ImGuizmo::ROTATE);
|
||||
static ImGuizmo::MODE mCurrentGizmoMode(ImGuizmo::WORLD);
|
||||
if (ImGui::IsKeyPressed(90))
|
||||
mCurrentGizmoOperation = ImGuizmo::TRANSLATE;
|
||||
if (ImGui::IsKeyPressed(69))
|
||||
mCurrentGizmoOperation = ImGuizmo::ROTATE;
|
||||
if (ImGui::IsKeyPressed(82)) // r Key
|
||||
mCurrentGizmoOperation = ImGuizmo::SCALE;
|
||||
if (ImGui::RadioButton("Translate", mCurrentGizmoOperation == ImGuizmo::TRANSLATE))
|
||||
mCurrentGizmoOperation = ImGuizmo::TRANSLATE;
|
||||
ImGui::SameLine();
|
||||
if (ImGui::RadioButton("Rotate", mCurrentGizmoOperation == ImGuizmo::ROTATE))
|
||||
mCurrentGizmoOperation = ImGuizmo::ROTATE;
|
||||
ImGui::SameLine();
|
||||
if (ImGui::RadioButton("Scale", mCurrentGizmoOperation == ImGuizmo::SCALE))
|
||||
mCurrentGizmoOperation = ImGuizmo::SCALE;
|
||||
float matrixTranslation[3], matrixRotation[3], matrixScale[3];
|
||||
ImGuizmo::DecomposeMatrixToComponents(matrix.m16, matrixTranslation, matrixRotation, matrixScale);
|
||||
ImGui::InputFloat3("Tr", matrixTranslation, 3);
|
||||
ImGui::InputFloat3("Rt", matrixRotation, 3);
|
||||
ImGui::InputFloat3("Sc", matrixScale, 3);
|
||||
ImGuizmo::RecomposeMatrixFromComponents(matrixTranslation, matrixRotation, matrixScale, matrix.m16);
|
||||
|
||||
if (mCurrentGizmoOperation != ImGuizmo::SCALE)
|
||||
{
|
||||
if (ImGui::RadioButton("Local", mCurrentGizmoMode == ImGuizmo::LOCAL))
|
||||
mCurrentGizmoMode = ImGuizmo::LOCAL;
|
||||
ImGui::SameLine();
|
||||
if (ImGui::RadioButton("World", mCurrentGizmoMode == ImGuizmo::WORLD))
|
||||
mCurrentGizmoMode = ImGuizmo::WORLD;
|
||||
}
|
||||
static bool useSnap(false);
|
||||
if (ImGui::IsKeyPressed(83))
|
||||
useSnap = !useSnap;
|
||||
ImGui::Checkbox("", &useSnap);
|
||||
ImGui::SameLine();
|
||||
vec_t snap;
|
||||
switch (mCurrentGizmoOperation)
|
||||
{
|
||||
case ImGuizmo::TRANSLATE:
|
||||
snap = config.mSnapTranslation;
|
||||
ImGui::InputFloat3("Snap", &snap.x);
|
||||
break;
|
||||
case ImGuizmo::ROTATE:
|
||||
snap = config.mSnapRotation;
|
||||
ImGui::InputFloat("Angle Snap", &snap.x);
|
||||
break;
|
||||
case ImGuizmo::SCALE:
|
||||
snap = config.mSnapScale;
|
||||
ImGui::InputFloat("Scale Snap", &snap.x);
|
||||
break;
|
||||
}
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);
|
||||
ImGuizmo::Manipulate(camera.mView.m16, camera.mProjection.m16, mCurrentGizmoOperation, mCurrentGizmoMode, matrix.m16, NULL, useSnap ? &snap.x : NULL);
|
||||
}
|
||||
#endif
|
||||
#pragma once
|
||||
|
||||
#ifdef USE_IMGUI_API
|
||||
#include "imconfig.h"
|
||||
#endif
|
||||
#ifndef IMGUI_API
|
||||
#define IMGUI_API
|
||||
#endif
|
||||
|
||||
#ifndef IMGUIZMO_NAMESPACE
|
||||
#define IMGUIZMO_NAMESPACE ImGuizmo
|
||||
#endif
|
||||
|
||||
namespace IMGUIZMO_NAMESPACE
|
||||
{
|
||||
// call inside your own window and before Manipulate() in order to draw gizmo to that window.
|
||||
// Or pass a specific ImDrawList to draw to (e.g. ImGui::GetForegroundDrawList()).
|
||||
IMGUI_API void SetDrawlist(ImDrawList* drawlist = nullptr);
|
||||
|
||||
// call BeginFrame right after ImGui_XXXX_NewFrame();
|
||||
IMGUI_API void BeginFrame();
|
||||
|
||||
// this is necessary because when imguizmo is compiled into a dll, and imgui into another
|
||||
// globals are not shared between them.
|
||||
// More details at https://stackoverflow.com/questions/19373061/what-happens-to-global-and-static-variables-in-a-shared-library-when-it-is-dynam
|
||||
// expose method to set imgui context
|
||||
IMGUI_API void SetImGuiContext(ImGuiContext* ctx);
|
||||
|
||||
// return true if mouse cursor is over any gizmo control (axis, plan or screen component)
|
||||
IMGUI_API bool IsOver();
|
||||
|
||||
// return true if mouse IsOver or if the gizmo is in moving state
|
||||
IMGUI_API bool IsUsing();
|
||||
|
||||
// return true if any gizmo is in moving state
|
||||
IMGUI_API bool IsUsingAny();
|
||||
|
||||
// enable/disable the gizmo. Stay in the state until next call to Enable.
|
||||
// gizmo is rendered with gray half transparent color when disabled
|
||||
IMGUI_API void Enable(bool enable);
|
||||
|
||||
// helper functions for manualy editing translation/rotation/scale with an input float
|
||||
// translation, rotation and scale float points to 3 floats each
|
||||
// Angles are in degrees (more suitable for human editing)
|
||||
// example:
|
||||
// float matrixTranslation[3], matrixRotation[3], matrixScale[3];
|
||||
// ImGuizmo::DecomposeMatrixToComponents(gizmoMatrix.m16, matrixTranslation, matrixRotation, matrixScale);
|
||||
// ImGui::InputFloat3("Tr", matrixTranslation, 3);
|
||||
// ImGui::InputFloat3("Rt", matrixRotation, 3);
|
||||
// ImGui::InputFloat3("Sc", matrixScale, 3);
|
||||
// ImGuizmo::RecomposeMatrixFromComponents(matrixTranslation, matrixRotation, matrixScale, gizmoMatrix.m16);
|
||||
//
|
||||
// These functions have some numerical stability issues for now. Use with caution.
|
||||
IMGUI_API void DecomposeMatrixToComponents(const float* matrix, float* translation, float* rotation, float* scale);
|
||||
IMGUI_API void RecomposeMatrixFromComponents(const float* translation, const float* rotation, const float* scale, float* matrix);
|
||||
|
||||
IMGUI_API void SetRect(float x, float y, float width, float height);
|
||||
// default is false
|
||||
IMGUI_API void SetOrthographic(bool isOrthographic);
|
||||
|
||||
// Render a cube with face color corresponding to face normal. Usefull for debug/tests
|
||||
IMGUI_API void DrawCubes(const float* view, const float* projection, const float* matrices, int matrixCount);
|
||||
IMGUI_API void DrawGrid(const float* view, const float* projection, const float* matrix, const float gridSize);
|
||||
|
||||
// call it when you want a gizmo
|
||||
// Needs view and projection matrices.
|
||||
// matrix parameter is the source matrix (where will be gizmo be drawn) and might be transformed by the function. Return deltaMatrix is optional
|
||||
// translation is applied in world space
|
||||
enum OPERATION
|
||||
{
|
||||
TRANSLATE_X = (1u << 0),
|
||||
TRANSLATE_Y = (1u << 1),
|
||||
TRANSLATE_Z = (1u << 2),
|
||||
ROTATE_X = (1u << 3),
|
||||
ROTATE_Y = (1u << 4),
|
||||
ROTATE_Z = (1u << 5),
|
||||
ROTATE_SCREEN = (1u << 6),
|
||||
SCALE_X = (1u << 7),
|
||||
SCALE_Y = (1u << 8),
|
||||
SCALE_Z = (1u << 9),
|
||||
BOUNDS = (1u << 10),
|
||||
SCALE_XU = (1u << 11),
|
||||
SCALE_YU = (1u << 12),
|
||||
SCALE_ZU = (1u << 13),
|
||||
|
||||
TRANSLATE = TRANSLATE_X | TRANSLATE_Y | TRANSLATE_Z,
|
||||
ROTATE = ROTATE_X | ROTATE_Y | ROTATE_Z | ROTATE_SCREEN,
|
||||
SCALE = SCALE_X | SCALE_Y | SCALE_Z,
|
||||
SCALEU = SCALE_XU | SCALE_YU | SCALE_ZU, // universal
|
||||
UNIVERSAL = TRANSLATE | ROTATE | SCALEU
|
||||
};
|
||||
|
||||
inline OPERATION operator|(OPERATION lhs, OPERATION rhs)
|
||||
{
|
||||
return static_cast<OPERATION>(static_cast<int>(lhs) | static_cast<int>(rhs));
|
||||
}
|
||||
|
||||
enum MODE
|
||||
{
|
||||
LOCAL,
|
||||
WORLD
|
||||
};
|
||||
|
||||
IMGUI_API bool Manipulate(const float* view, const float* projection, OPERATION operation, MODE mode, float* matrix, float* deltaMatrix = NULL, const float* snap = NULL, const float* localBounds = NULL, const float* boundsSnap = NULL);
|
||||
//
|
||||
// Please note that this cubeview is patented by Autodesk : https://patents.google.com/patent/US7782319B2/en
|
||||
// It seems to be a defensive patent in the US. I don't think it will bring troubles using it as
|
||||
// other software are using the same mechanics. But just in case, you are now warned!
|
||||
//
|
||||
IMGUI_API void ViewManipulate(float* view, float length, ImVec2 position, ImVec2 size, ImU32 backgroundColor);
|
||||
|
||||
// use this version if you did not call Manipulate before and you are just using ViewManipulate
|
||||
IMGUI_API void ViewManipulate(float* view, const float* projection, OPERATION operation, MODE mode, float* matrix, float length, ImVec2 position, ImVec2 size, ImU32 backgroundColor);
|
||||
|
||||
IMGUI_API void SetID(int id);
|
||||
|
||||
// return true if the cursor is over the operation's gizmo
|
||||
IMGUI_API bool IsOver(OPERATION op);
|
||||
IMGUI_API void SetGizmoSizeClipSpace(float value);
|
||||
|
||||
// Allow axis to flip
|
||||
// When true (default), the guizmo axis flip for better visibility
|
||||
// When false, they always stay along the positive world/local axis
|
||||
IMGUI_API void AllowAxisFlip(bool value);
|
||||
|
||||
// Configure the limit where axis are hidden
|
||||
IMGUI_API void SetAxisLimit(float value);
|
||||
// Configure the limit where planes are hiden
|
||||
IMGUI_API void SetPlaneLimit(float value);
|
||||
|
||||
enum COLOR
|
||||
{
|
||||
DIRECTION_X, // directionColor[0]
|
||||
DIRECTION_Y, // directionColor[1]
|
||||
DIRECTION_Z, // directionColor[2]
|
||||
PLANE_X, // planeColor[0]
|
||||
PLANE_Y, // planeColor[1]
|
||||
PLANE_Z, // planeColor[2]
|
||||
SELECTION, // selectionColor
|
||||
INACTIVE, // inactiveColor
|
||||
TRANSLATION_LINE, // translationLineColor
|
||||
SCALE_LINE,
|
||||
ROTATION_USING_BORDER,
|
||||
ROTATION_USING_FILL,
|
||||
HATCHED_AXIS_LINES,
|
||||
TEXT,
|
||||
TEXT_SHADOW,
|
||||
COUNT
|
||||
};
|
||||
|
||||
struct Style
|
||||
{
|
||||
IMGUI_API Style();
|
||||
|
||||
float TranslationLineThickness; // Thickness of lines for translation gizmo
|
||||
float TranslationLineArrowSize; // Size of arrow at the end of lines for translation gizmo
|
||||
float RotationLineThickness; // Thickness of lines for rotation gizmo
|
||||
float RotationOuterLineThickness; // Thickness of line surrounding the rotation gizmo
|
||||
float ScaleLineThickness; // Thickness of lines for scale gizmo
|
||||
float ScaleLineCircleSize; // Size of circle at the end of lines for scale gizmo
|
||||
float HatchedAxisLineThickness; // Thickness of hatched axis lines
|
||||
float CenterCircleSize; // Size of circle at the center of the translate/scale gizmo
|
||||
|
||||
ImVec4 Colors[COLOR::COUNT];
|
||||
};
|
||||
|
||||
IMGUI_API Style& GetStyle();
|
||||
}
|
||||
245
source/thirdparty/imgui/ImZoomSlider.h
vendored
245
source/thirdparty/imgui/ImZoomSlider.h
vendored
@@ -1,245 +0,0 @@
|
||||
// https://github.com/CedricGuillemet/ImGuizmo
|
||||
// v 1.89 WIP
|
||||
//
|
||||
// The MIT License(MIT)
|
||||
//
|
||||
// Copyright(c) 2021 Cedric Guillemet
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files(the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions :
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
#pragma once
|
||||
|
||||
namespace ImZoomSlider
|
||||
{
|
||||
typedef int ImGuiZoomSliderFlags;
|
||||
enum ImGuiPopupFlags_
|
||||
{
|
||||
ImGuiZoomSliderFlags_None = 0,
|
||||
ImGuiZoomSliderFlags_Vertical = 1,
|
||||
ImGuiZoomSliderFlags_NoAnchors = 2,
|
||||
ImGuiZoomSliderFlags_NoMiddleCarets = 4,
|
||||
ImGuiZoomSliderFlags_NoWheel = 8,
|
||||
};
|
||||
|
||||
template<typename T> bool ImZoomSlider(const T lower, const T higher, T& viewLower, T& viewHigher, float wheelRatio = 0.01f, ImGuiZoomSliderFlags flags = ImGuiZoomSliderFlags_None)
|
||||
{
|
||||
bool interacted = false;
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImDrawList* draw_list = ImGui::GetWindowDrawList();
|
||||
|
||||
static const float handleSize = 12;
|
||||
static const float roundRadius = 3.f;
|
||||
static const char* controlName = "ImZoomSlider";
|
||||
|
||||
static bool movingScrollBarSvg = false;
|
||||
static bool sizingRBarSvg = false;
|
||||
static bool sizingLBarSvg = false;
|
||||
static ImGuiID editingId = (ImGuiID)-1;
|
||||
static float scrollingSource = 0.f;
|
||||
static float saveViewLower;
|
||||
static float saveViewHigher;
|
||||
|
||||
const bool isVertical = flags & ImGuiZoomSliderFlags_Vertical;
|
||||
const ImVec2 canvasPos = ImGui::GetCursorScreenPos();
|
||||
const ImVec2 canvasSize = ImGui::GetContentRegionAvail();
|
||||
const float canvasSizeLength = isVertical ? ImGui::GetItemRectSize().y : canvasSize.x;
|
||||
const ImVec2 scrollBarSize = isVertical ? ImVec2(14.f, canvasSizeLength) : ImVec2(canvasSizeLength, 14.f);
|
||||
|
||||
ImGui::InvisibleButton(controlName, scrollBarSize);
|
||||
const ImGuiID currentId = ImGui::GetID(controlName);
|
||||
|
||||
const bool usingEditingId = currentId == editingId;
|
||||
const bool canUseControl = usingEditingId || editingId == -1;
|
||||
const bool movingScrollBar = usingEditingId ? movingScrollBarSvg : false;
|
||||
const bool sizingRBar = usingEditingId ? sizingRBarSvg : false;
|
||||
const bool sizingLBar = usingEditingId ? sizingLBarSvg : false;
|
||||
const int componentIndex = isVertical ? 1 : 0;
|
||||
const ImVec2 scrollBarMin = ImGui::GetItemRectMin();
|
||||
const ImVec2 scrollBarMax = ImGui::GetItemRectMax();
|
||||
const ImVec2 scrollBarA = ImVec2(scrollBarMin.x, scrollBarMin.y) - (isVertical ? ImVec2(2,0) : ImVec2(0,2));
|
||||
const ImVec2 scrollBarB = isVertical ? ImVec2(scrollBarMax.x - 1.f, scrollBarMin.y + canvasSizeLength) : ImVec2(scrollBarMin.x + canvasSizeLength, scrollBarMax.y - 1.f);
|
||||
const float scrollStart = ((viewLower - lower) / (higher - lower)) * canvasSizeLength + scrollBarMin[componentIndex];
|
||||
const float scrollEnd = ((viewHigher - lower) / (higher - lower)) * canvasSizeLength + scrollBarMin[componentIndex];
|
||||
const float screenSize = scrollEnd - scrollStart;
|
||||
const ImVec2 scrollTopLeft = isVertical ? ImVec2(scrollBarMin.x, scrollStart) : ImVec2(scrollStart, scrollBarMin.y);
|
||||
const ImVec2 scrollBottomRight = isVertical ? ImVec2(scrollBarMax.x - 2.f, scrollEnd) : ImVec2(scrollEnd, scrollBarMax.y - 2.f);
|
||||
const bool inScrollBar = canUseControl && ImRect(scrollTopLeft, scrollBottomRight).Contains(io.MousePos);
|
||||
const ImRect scrollBarRect(scrollBarA, scrollBarB);
|
||||
const float deltaScreen = io.MousePos[componentIndex] - scrollingSource;
|
||||
const float deltaView = ((higher - lower) / canvasSizeLength) * deltaScreen;
|
||||
const uint32_t barColor = ImGui::GetColorU32((inScrollBar || movingScrollBar) ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
|
||||
const float middleCoord = (scrollStart + scrollEnd) * 0.5f;
|
||||
const bool insideControl = canUseControl && ImRect(scrollBarMin, scrollBarMax).Contains(io.MousePos);
|
||||
const bool hasAnchors = !(flags & ImGuiZoomSliderFlags_NoAnchors);
|
||||
const float viewMinSize = ((3.f * handleSize) / canvasSizeLength) * (higher - lower);
|
||||
const auto ClipView = [lower, higher, &viewLower, &viewHigher]() {
|
||||
if (viewLower < lower)
|
||||
{
|
||||
const float deltaClip = lower - viewLower;
|
||||
viewLower += deltaClip;
|
||||
viewHigher += deltaClip;
|
||||
}
|
||||
if (viewHigher > higher)
|
||||
{
|
||||
const float deltaClip = viewHigher - higher;
|
||||
viewLower -= deltaClip;
|
||||
viewHigher -= deltaClip;
|
||||
}
|
||||
};
|
||||
|
||||
bool onLeft = false;
|
||||
bool onRight = false;
|
||||
|
||||
draw_list->AddRectFilled(scrollBarA, scrollBarB, 0xFF101010, roundRadius);
|
||||
draw_list->AddRectFilled(scrollBarA, scrollBarB, 0xFF222222, 0);
|
||||
draw_list->AddRectFilled(scrollTopLeft, scrollBottomRight, barColor, roundRadius);
|
||||
|
||||
if (!(flags & ImGuiZoomSliderFlags_NoMiddleCarets))
|
||||
{
|
||||
for (float i = 0.5f; i < 3.f; i += 1.f)
|
||||
{
|
||||
const float coordA = middleCoord - handleSize * 0.5f;
|
||||
const float coordB = middleCoord + handleSize * 0.5f;
|
||||
ImVec2 base = scrollBarMin;
|
||||
base.x += scrollBarSize.x * 0.25f * i;
|
||||
base.y += scrollBarSize.y * 0.25f * i;
|
||||
|
||||
if (isVertical)
|
||||
{
|
||||
draw_list->AddLine(ImVec2(base.x, coordA), ImVec2(base.x, coordB), ImGui::GetColorU32(ImGuiCol_SliderGrab));
|
||||
}
|
||||
else
|
||||
{
|
||||
draw_list->AddLine(ImVec2(coordA, base.y), ImVec2(coordB, base.y), ImGui::GetColorU32(ImGuiCol_SliderGrab));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mouse wheel
|
||||
if (io.MouseClicked[0] && insideControl && !inScrollBar)
|
||||
{
|
||||
const float ratio = (io.MousePos[componentIndex] - scrollBarMin[componentIndex]) / (scrollBarMax[componentIndex] - scrollBarMin[componentIndex]);
|
||||
const float size = (higher - lower);
|
||||
const float halfViewSize = (viewHigher - viewLower) * 0.5f;
|
||||
const float middle = ratio * size + lower;
|
||||
viewLower = middle - halfViewSize;
|
||||
viewHigher = middle + halfViewSize;
|
||||
ClipView();
|
||||
interacted = true;
|
||||
}
|
||||
|
||||
if (!(flags & ImGuiZoomSliderFlags_NoWheel) && inScrollBar && fabsf(io.MouseWheel) > 0.f)
|
||||
{
|
||||
const float ratio = (io.MousePos[componentIndex] - scrollStart) / (scrollEnd - scrollStart);
|
||||
const float amount = io.MouseWheel * wheelRatio * (viewHigher - viewLower);
|
||||
|
||||
viewLower -= ratio * amount;
|
||||
viewHigher += (1.f - ratio) * amount;
|
||||
ClipView();
|
||||
interacted = true;
|
||||
}
|
||||
|
||||
if (screenSize > handleSize * 2.f && hasAnchors)
|
||||
{
|
||||
const ImRect barHandleLeft(scrollTopLeft, isVertical ? ImVec2(scrollBottomRight.x, scrollTopLeft.y + handleSize) : ImVec2(scrollTopLeft.x + handleSize, scrollBottomRight.y));
|
||||
const ImRect barHandleRight(isVertical ? ImVec2(scrollTopLeft.x, scrollBottomRight.y - handleSize) : ImVec2(scrollBottomRight.x - handleSize, scrollTopLeft.y), scrollBottomRight);
|
||||
|
||||
onLeft = barHandleLeft.Contains(io.MousePos);
|
||||
onRight = barHandleRight.Contains(io.MousePos);
|
||||
|
||||
draw_list->AddRectFilled(barHandleLeft.Min, barHandleLeft.Max, ImGui::GetColorU32((onLeft || sizingLBar) ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), roundRadius);
|
||||
draw_list->AddRectFilled(barHandleRight.Min, barHandleRight.Max, ImGui::GetColorU32((onRight || sizingRBar) ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), roundRadius);
|
||||
}
|
||||
|
||||
if (sizingRBar)
|
||||
{
|
||||
if (!io.MouseDown[0])
|
||||
{
|
||||
sizingRBarSvg = false;
|
||||
editingId = (ImGuiID)-1;
|
||||
}
|
||||
else
|
||||
{
|
||||
viewHigher = ImMin(saveViewHigher + deltaView, higher);
|
||||
}
|
||||
}
|
||||
else if (sizingLBar)
|
||||
{
|
||||
if (!io.MouseDown[0])
|
||||
{
|
||||
sizingLBarSvg = false;
|
||||
editingId = (ImGuiID)-1;
|
||||
}
|
||||
else
|
||||
{
|
||||
viewLower = ImMax(saveViewLower + deltaView, lower);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (movingScrollBar)
|
||||
{
|
||||
if (!io.MouseDown[0])
|
||||
{
|
||||
movingScrollBarSvg = false;
|
||||
editingId = (ImGuiID)-1;
|
||||
}
|
||||
else
|
||||
{
|
||||
viewLower = saveViewLower + deltaView;
|
||||
viewHigher = saveViewHigher + deltaView;
|
||||
ClipView();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (inScrollBar && ImGui::IsMouseClicked(0))
|
||||
{
|
||||
movingScrollBarSvg = true;
|
||||
scrollingSource = io.MousePos[componentIndex];
|
||||
saveViewLower = viewLower;
|
||||
saveViewHigher = viewHigher;
|
||||
editingId = currentId;
|
||||
}
|
||||
if (!sizingRBar && onRight && ImGui::IsMouseClicked(0) && hasAnchors)
|
||||
{
|
||||
sizingRBarSvg = true;
|
||||
editingId = currentId;
|
||||
}
|
||||
if (!sizingLBar && onLeft && ImGui::IsMouseClicked(0) && hasAnchors)
|
||||
{
|
||||
sizingLBarSvg = true;
|
||||
editingId = currentId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// minimal size check
|
||||
if ((viewHigher - viewLower) < viewMinSize)
|
||||
{
|
||||
const float middle = (viewLower + viewHigher) * 0.5f;
|
||||
viewLower = middle - viewMinSize * 0.5f;
|
||||
viewHigher = middle + viewMinSize * 0.5f;
|
||||
ClipView();
|
||||
}
|
||||
|
||||
return movingScrollBar || sizingRBar || sizingLBar || interacted;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -1,670 +0,0 @@
|
||||
// dear imgui: Renderer + Platform Backend for Allegro 5
|
||||
// (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Clipboard support (from Allegro 5.1.12).
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// Missing features or Issues:
|
||||
// [ ] Renderer: The renderer is suboptimal as we need to convert vertices manually.
|
||||
// [ ] Platform: Missing gamepad support.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-07-07: Fixed texture update broken on some platforms where ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten.
|
||||
// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture().
|
||||
// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support.
|
||||
// 2025-01-06: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256).
|
||||
// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
|
||||
// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
|
||||
// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
|
||||
// 2022-11-30: Renderer: Restoring using al_draw_indexed_prim() when Allegro version is >= 5.2.5.
|
||||
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
|
||||
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
|
||||
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
|
||||
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
|
||||
// 2022-01-17: Inputs: always calling io.AddKeyModsEvent() next and before key event (not in NewFrame) to fix input queue with very low framerates.
|
||||
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
|
||||
// 2021-12-08: Renderer: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
|
||||
// 2021-08-17: Calling io.AddFocusEvent() on ALLEGRO_EVENT_DISPLAY_SWITCH_OUT/ALLEGRO_EVENT_DISPLAY_SWITCH_IN events.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-05-19: Renderer: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-02-18: Change blending equation to preserve alpha in output buffer.
|
||||
// 2020-08-10: Inputs: Fixed horizontal mouse wheel direction.
|
||||
// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
|
||||
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
|
||||
// 2019-05-11: Inputs: Don't filter character value from ALLEGRO_EVENT_KEY_CHAR before calling AddInputCharacter().
|
||||
// 2019-04-30: Renderer: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2018-11-30: Platform: Added touchscreen support.
|
||||
// 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window.
|
||||
// 2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12).
|
||||
// 2018-06-13: Renderer: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
|
||||
// 2018-06-13: Renderer: Stopped using al_draw_indexed_prim() as it is buggy in Allegro's DX9 backend.
|
||||
// 2018-06-13: Renderer: Backup/restore transform and clipping rectangle.
|
||||
// 2018-06-11: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
|
||||
// 2018-04-18: Misc: Renamed file from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp.
|
||||
// 2018-04-18: Misc: Added support for 32-bit vertex indices to avoid conversion at runtime. Added imconfig_allegro5.h to enforce 32-bit indices when included from imgui.h.
|
||||
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplAllegro5_RenderDrawData() in the .h file so you can call it yourself.
|
||||
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
|
||||
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_allegro5.h"
|
||||
#include <stdint.h> // uint64_t
|
||||
#include <cstring> // memcpy
|
||||
|
||||
// Allegro
|
||||
#include <allegro5/allegro.h>
|
||||
#include <allegro5/allegro_primitives.h>
|
||||
#ifdef _WIN32
|
||||
#include <allegro5/allegro_windows.h>
|
||||
#endif
|
||||
#define ALLEGRO_HAS_CLIPBOARD ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12
|
||||
#define ALLEGRO_HAS_DRAW_INDEXED_PRIM ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (2 << 16) | ( 5 << 8))) // DX9 implementation of al_draw_indexed_prim() got fixed in Allegro 5.2.5
|
||||
|
||||
// Visual Studio warnings
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning (disable: 4127) // condition expression is constant
|
||||
#endif
|
||||
|
||||
struct ImDrawVertAllegro
|
||||
{
|
||||
ImVec2 pos;
|
||||
ImVec2 uv;
|
||||
ALLEGRO_COLOR col;
|
||||
};
|
||||
|
||||
// FIXME-OPT: Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 float as well..
|
||||
// FIXME-OPT: Consider inlining al_map_rgba()?
|
||||
// see https://github.com/liballeg/allegro5/blob/master/src/pixels.c#L554
|
||||
// and https://github.com/liballeg/allegro5/blob/master/include/allegro5/internal/aintern_pixels.h
|
||||
#define DRAW_VERT_IMGUI_TO_ALLEGRO(DST, SRC) { (DST)->pos = (SRC)->pos; (DST)->uv = (SRC)->uv; unsigned char* c = (unsigned char*)&(SRC)->col; (DST)->col = al_map_rgba(c[0], c[1], c[2], c[3]); }
|
||||
|
||||
// Allegro Data
|
||||
struct ImGui_ImplAllegro5_Data
|
||||
{
|
||||
ALLEGRO_DISPLAY* Display;
|
||||
ALLEGRO_BITMAP* Texture;
|
||||
double Time;
|
||||
ALLEGRO_MOUSE_CURSOR* MouseCursorInvisible;
|
||||
ALLEGRO_VERTEX_DECL* VertexDecl;
|
||||
char* ClipboardTextData;
|
||||
ImGuiMouseCursor LastCursor;
|
||||
|
||||
ImVector<ImDrawVertAllegro> BufVertices;
|
||||
ImVector<int> BufIndices;
|
||||
|
||||
ImGui_ImplAllegro5_Data() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
|
||||
static ImGui_ImplAllegro5_Data* ImGui_ImplAllegro5_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplAllegro5_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; }
|
||||
|
||||
static void ImGui_ImplAllegro5_SetupRenderState(ImDrawData* draw_data)
|
||||
{
|
||||
// Setup blending
|
||||
al_set_separate_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
|
||||
|
||||
// Setup orthographic projection matrix
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
|
||||
{
|
||||
float L = draw_data->DisplayPos.x;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
|
||||
float T = draw_data->DisplayPos.y;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
|
||||
ALLEGRO_TRANSFORM transform;
|
||||
al_identity_transform(&transform);
|
||||
al_use_transform(&transform);
|
||||
al_orthographic_transform(&transform, L, T, 1.0f, R, B, -1.0f);
|
||||
al_use_projection_transform(&transform);
|
||||
}
|
||||
}
|
||||
|
||||
// Render function.
|
||||
void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
// Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
|
||||
// (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
|
||||
if (draw_data->Textures != nullptr)
|
||||
for (ImTextureData* tex : *draw_data->Textures)
|
||||
if (tex->Status != ImTextureStatus_OK)
|
||||
ImGui_ImplAllegro5_UpdateTexture(tex);
|
||||
|
||||
// Backup Allegro state that will be modified
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
ALLEGRO_TRANSFORM last_transform = *al_get_current_transform();
|
||||
ALLEGRO_TRANSFORM last_projection_transform = *al_get_current_projection_transform();
|
||||
int last_clip_x, last_clip_y, last_clip_w, last_clip_h;
|
||||
al_get_clipping_rectangle(&last_clip_x, &last_clip_y, &last_clip_w, &last_clip_h);
|
||||
int last_blender_op, last_blender_src, last_blender_dst;
|
||||
al_get_blender(&last_blender_op, &last_blender_src, &last_blender_dst);
|
||||
|
||||
// Setup desired render state
|
||||
ImGui_ImplAllegro5_SetupRenderState(draw_data);
|
||||
|
||||
// Render command lists
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
|
||||
ImVector<ImDrawVertAllegro>& vertices = bd->BufVertices;
|
||||
#if ALLEGRO_HAS_DRAW_INDEXED_PRIM
|
||||
vertices.resize(draw_list->VtxBuffer.Size);
|
||||
for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
|
||||
{
|
||||
const ImDrawVert* src_v = &draw_list->VtxBuffer[i];
|
||||
ImDrawVertAllegro* dst_v = &vertices[i];
|
||||
DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
|
||||
}
|
||||
const int* indices = nullptr;
|
||||
if (sizeof(ImDrawIdx) == 2)
|
||||
{
|
||||
// FIXME-OPT: Allegro doesn't support 16-bit indices.
|
||||
// You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices.
|
||||
// Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful.
|
||||
bd->BufIndices.resize(draw_list->IdxBuffer.Size);
|
||||
for (int i = 0; i < draw_list->IdxBuffer.Size; ++i)
|
||||
bd->BufIndices[i] = (int)draw_list->IdxBuffer.Data[i];
|
||||
indices = bd->BufIndices.Data;
|
||||
}
|
||||
else if (sizeof(ImDrawIdx) == 4)
|
||||
{
|
||||
indices = (const int*)draw_list->IdxBuffer.Data;
|
||||
}
|
||||
#else
|
||||
// Allegro's implementation of al_draw_indexed_prim() for DX9 was broken until 5.2.5. Unindex buffers ourselves while converting vertex format.
|
||||
vertices.resize(draw_list->IdxBuffer.Size);
|
||||
for (int i = 0; i < draw_list->IdxBuffer.Size; i++)
|
||||
{
|
||||
const ImDrawVert* src_v = &draw_list->VtxBuffer[draw_list->IdxBuffer[i]];
|
||||
ImDrawVertAllegro* dst_v = &vertices[i];
|
||||
DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Render command lists
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplAllegro5_SetupRenderState(draw_data);
|
||||
else
|
||||
pcmd->UserCallback(draw_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
|
||||
ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
|
||||
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle, Draw
|
||||
ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->GetTexID();
|
||||
al_set_clipping_rectangle(clip_min.x, clip_min.y, clip_max.x - clip_min.x, clip_max.y - clip_min.y);
|
||||
#if ALLEGRO_HAS_DRAW_INDEXED_PRIM
|
||||
al_draw_indexed_prim(&vertices[0], bd->VertexDecl, texture, &indices[pcmd->IdxOffset], pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST);
|
||||
#else
|
||||
al_draw_prim(&vertices[0], bd->VertexDecl, texture, pcmd->IdxOffset, pcmd->IdxOffset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore modified Allegro state
|
||||
al_set_blender(last_blender_op, last_blender_src, last_blender_dst);
|
||||
al_set_clipping_rectangle(last_clip_x, last_clip_y, last_clip_w, last_clip_h);
|
||||
al_use_transform(&last_transform);
|
||||
al_use_projection_transform(&last_projection_transform);
|
||||
}
|
||||
|
||||
bool ImGui_ImplAllegro5_CreateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
|
||||
// Create an invisible mouse cursor
|
||||
// Because al_hide_mouse_cursor() seems to mess up with the actual inputs..
|
||||
ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8, 8);
|
||||
bd->MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0);
|
||||
al_destroy_bitmap(mouse_cursor);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex)
|
||||
{
|
||||
if (tex->Status == ImTextureStatus_WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
|
||||
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
|
||||
// Create texture
|
||||
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
|
||||
const int new_bitmap_flags = al_get_new_bitmap_flags();
|
||||
int new_bitmap_format = al_get_new_bitmap_format();
|
||||
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);
|
||||
al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE);
|
||||
ALLEGRO_BITMAP* cpu_bitmap = al_create_bitmap(tex->Width, tex->Height);
|
||||
al_set_new_bitmap_flags(new_bitmap_flags);
|
||||
al_set_new_bitmap_format(new_bitmap_format);
|
||||
IM_ASSERT(cpu_bitmap != nullptr && "Backend failed to create texture!");
|
||||
|
||||
// Upload pixels
|
||||
ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap(cpu_bitmap, al_get_bitmap_format(cpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
|
||||
IM_ASSERT(locked_region != nullptr && "Backend failed to create texture!");
|
||||
memcpy(locked_region->data, tex->GetPixels(), tex->GetSizeInBytes());
|
||||
al_unlock_bitmap(cpu_bitmap);
|
||||
|
||||
// Convert software texture to hardware texture.
|
||||
ALLEGRO_BITMAP* gpu_bitmap = al_clone_bitmap(cpu_bitmap);
|
||||
al_destroy_bitmap(cpu_bitmap);
|
||||
IM_ASSERT(gpu_bitmap != nullptr && "Backend failed to create texture!");
|
||||
|
||||
// Store identifiers
|
||||
tex->SetTexID((ImTextureID)(intptr_t)gpu_bitmap);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantUpdates)
|
||||
{
|
||||
// Update selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
|
||||
ImTextureRect r = tex->UpdateRect; // Bounding box encompassing all individual updates
|
||||
ALLEGRO_BITMAP* gpu_bitmap = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
|
||||
ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap_region(gpu_bitmap, r.x, r.y, r.w, r.h, al_get_bitmap_format(gpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
|
||||
IM_ASSERT(locked_region && "Backend failed to update texture!");
|
||||
for (int y = 0; y < r.h; y++)
|
||||
memcpy((unsigned char*)locked_region->data + locked_region->pitch * y, tex->GetPixelsAt(r.x, r.y + y), r.w * tex->BytesPerPixel); // dst, src, block pitch
|
||||
al_unlock_bitmap(gpu_bitmap);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantDestroy)
|
||||
{
|
||||
ALLEGRO_BITMAP* backend_tex = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
|
||||
if (backend_tex)
|
||||
al_destroy_bitmap(backend_tex);
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex->SetTexID(ImTextureID_Invalid);
|
||||
tex->SetStatus(ImTextureStatus_Destroyed);
|
||||
}
|
||||
}
|
||||
|
||||
void ImGui_ImplAllegro5_InvalidateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
|
||||
// Destroy all textures
|
||||
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
|
||||
if (tex->RefCount == 1)
|
||||
{
|
||||
tex->SetStatus(ImTextureStatus_WantDestroy);
|
||||
ImGui_ImplAllegro5_UpdateTexture(tex);
|
||||
}
|
||||
|
||||
// Destroy mouse cursor
|
||||
if (bd->MouseCursorInvisible)
|
||||
{
|
||||
al_destroy_mouse_cursor(bd->MouseCursorInvisible);
|
||||
bd->MouseCursorInvisible = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
#if ALLEGRO_HAS_CLIPBOARD
|
||||
static const char* ImGui_ImplAllegro5_GetClipboardText(ImGuiContext*)
|
||||
{
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
if (bd->ClipboardTextData)
|
||||
al_free(bd->ClipboardTextData);
|
||||
bd->ClipboardTextData = al_get_clipboard_text(bd->Display);
|
||||
return bd->ClipboardTextData;
|
||||
}
|
||||
|
||||
static void ImGui_ImplAllegro5_SetClipboardText(ImGuiContext*, const char* text)
|
||||
{
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
al_set_clipboard_text(bd->Display, text);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Not static to allow third-party code to use that if they want to (but undocumented)
|
||||
ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code);
|
||||
ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code)
|
||||
{
|
||||
switch (key_code)
|
||||
{
|
||||
case ALLEGRO_KEY_TAB: return ImGuiKey_Tab;
|
||||
case ALLEGRO_KEY_LEFT: return ImGuiKey_LeftArrow;
|
||||
case ALLEGRO_KEY_RIGHT: return ImGuiKey_RightArrow;
|
||||
case ALLEGRO_KEY_UP: return ImGuiKey_UpArrow;
|
||||
case ALLEGRO_KEY_DOWN: return ImGuiKey_DownArrow;
|
||||
case ALLEGRO_KEY_PGUP: return ImGuiKey_PageUp;
|
||||
case ALLEGRO_KEY_PGDN: return ImGuiKey_PageDown;
|
||||
case ALLEGRO_KEY_HOME: return ImGuiKey_Home;
|
||||
case ALLEGRO_KEY_END: return ImGuiKey_End;
|
||||
case ALLEGRO_KEY_INSERT: return ImGuiKey_Insert;
|
||||
case ALLEGRO_KEY_DELETE: return ImGuiKey_Delete;
|
||||
case ALLEGRO_KEY_BACKSPACE: return ImGuiKey_Backspace;
|
||||
case ALLEGRO_KEY_SPACE: return ImGuiKey_Space;
|
||||
case ALLEGRO_KEY_ENTER: return ImGuiKey_Enter;
|
||||
case ALLEGRO_KEY_ESCAPE: return ImGuiKey_Escape;
|
||||
case ALLEGRO_KEY_QUOTE: return ImGuiKey_Apostrophe;
|
||||
case ALLEGRO_KEY_COMMA: return ImGuiKey_Comma;
|
||||
case ALLEGRO_KEY_MINUS: return ImGuiKey_Minus;
|
||||
case ALLEGRO_KEY_FULLSTOP: return ImGuiKey_Period;
|
||||
case ALLEGRO_KEY_SLASH: return ImGuiKey_Slash;
|
||||
case ALLEGRO_KEY_SEMICOLON: return ImGuiKey_Semicolon;
|
||||
case ALLEGRO_KEY_EQUALS: return ImGuiKey_Equal;
|
||||
case ALLEGRO_KEY_OPENBRACE: return ImGuiKey_LeftBracket;
|
||||
case ALLEGRO_KEY_BACKSLASH: return ImGuiKey_Backslash;
|
||||
case ALLEGRO_KEY_CLOSEBRACE: return ImGuiKey_RightBracket;
|
||||
case ALLEGRO_KEY_TILDE: return ImGuiKey_GraveAccent;
|
||||
case ALLEGRO_KEY_CAPSLOCK: return ImGuiKey_CapsLock;
|
||||
case ALLEGRO_KEY_SCROLLLOCK: return ImGuiKey_ScrollLock;
|
||||
case ALLEGRO_KEY_NUMLOCK: return ImGuiKey_NumLock;
|
||||
case ALLEGRO_KEY_PRINTSCREEN: return ImGuiKey_PrintScreen;
|
||||
case ALLEGRO_KEY_PAUSE: return ImGuiKey_Pause;
|
||||
case ALLEGRO_KEY_PAD_0: return ImGuiKey_Keypad0;
|
||||
case ALLEGRO_KEY_PAD_1: return ImGuiKey_Keypad1;
|
||||
case ALLEGRO_KEY_PAD_2: return ImGuiKey_Keypad2;
|
||||
case ALLEGRO_KEY_PAD_3: return ImGuiKey_Keypad3;
|
||||
case ALLEGRO_KEY_PAD_4: return ImGuiKey_Keypad4;
|
||||
case ALLEGRO_KEY_PAD_5: return ImGuiKey_Keypad5;
|
||||
case ALLEGRO_KEY_PAD_6: return ImGuiKey_Keypad6;
|
||||
case ALLEGRO_KEY_PAD_7: return ImGuiKey_Keypad7;
|
||||
case ALLEGRO_KEY_PAD_8: return ImGuiKey_Keypad8;
|
||||
case ALLEGRO_KEY_PAD_9: return ImGuiKey_Keypad9;
|
||||
case ALLEGRO_KEY_PAD_DELETE: return ImGuiKey_KeypadDecimal;
|
||||
case ALLEGRO_KEY_PAD_SLASH: return ImGuiKey_KeypadDivide;
|
||||
case ALLEGRO_KEY_PAD_ASTERISK: return ImGuiKey_KeypadMultiply;
|
||||
case ALLEGRO_KEY_PAD_MINUS: return ImGuiKey_KeypadSubtract;
|
||||
case ALLEGRO_KEY_PAD_PLUS: return ImGuiKey_KeypadAdd;
|
||||
case ALLEGRO_KEY_PAD_ENTER: return ImGuiKey_KeypadEnter;
|
||||
case ALLEGRO_KEY_PAD_EQUALS: return ImGuiKey_KeypadEqual;
|
||||
case ALLEGRO_KEY_LCTRL: return ImGuiKey_LeftCtrl;
|
||||
case ALLEGRO_KEY_LSHIFT: return ImGuiKey_LeftShift;
|
||||
case ALLEGRO_KEY_ALT: return ImGuiKey_LeftAlt;
|
||||
case ALLEGRO_KEY_LWIN: return ImGuiKey_LeftSuper;
|
||||
case ALLEGRO_KEY_RCTRL: return ImGuiKey_RightCtrl;
|
||||
case ALLEGRO_KEY_RSHIFT: return ImGuiKey_RightShift;
|
||||
case ALLEGRO_KEY_ALTGR: return ImGuiKey_RightAlt;
|
||||
case ALLEGRO_KEY_RWIN: return ImGuiKey_RightSuper;
|
||||
case ALLEGRO_KEY_MENU: return ImGuiKey_Menu;
|
||||
case ALLEGRO_KEY_0: return ImGuiKey_0;
|
||||
case ALLEGRO_KEY_1: return ImGuiKey_1;
|
||||
case ALLEGRO_KEY_2: return ImGuiKey_2;
|
||||
case ALLEGRO_KEY_3: return ImGuiKey_3;
|
||||
case ALLEGRO_KEY_4: return ImGuiKey_4;
|
||||
case ALLEGRO_KEY_5: return ImGuiKey_5;
|
||||
case ALLEGRO_KEY_6: return ImGuiKey_6;
|
||||
case ALLEGRO_KEY_7: return ImGuiKey_7;
|
||||
case ALLEGRO_KEY_8: return ImGuiKey_8;
|
||||
case ALLEGRO_KEY_9: return ImGuiKey_9;
|
||||
case ALLEGRO_KEY_A: return ImGuiKey_A;
|
||||
case ALLEGRO_KEY_B: return ImGuiKey_B;
|
||||
case ALLEGRO_KEY_C: return ImGuiKey_C;
|
||||
case ALLEGRO_KEY_D: return ImGuiKey_D;
|
||||
case ALLEGRO_KEY_E: return ImGuiKey_E;
|
||||
case ALLEGRO_KEY_F: return ImGuiKey_F;
|
||||
case ALLEGRO_KEY_G: return ImGuiKey_G;
|
||||
case ALLEGRO_KEY_H: return ImGuiKey_H;
|
||||
case ALLEGRO_KEY_I: return ImGuiKey_I;
|
||||
case ALLEGRO_KEY_J: return ImGuiKey_J;
|
||||
case ALLEGRO_KEY_K: return ImGuiKey_K;
|
||||
case ALLEGRO_KEY_L: return ImGuiKey_L;
|
||||
case ALLEGRO_KEY_M: return ImGuiKey_M;
|
||||
case ALLEGRO_KEY_N: return ImGuiKey_N;
|
||||
case ALLEGRO_KEY_O: return ImGuiKey_O;
|
||||
case ALLEGRO_KEY_P: return ImGuiKey_P;
|
||||
case ALLEGRO_KEY_Q: return ImGuiKey_Q;
|
||||
case ALLEGRO_KEY_R: return ImGuiKey_R;
|
||||
case ALLEGRO_KEY_S: return ImGuiKey_S;
|
||||
case ALLEGRO_KEY_T: return ImGuiKey_T;
|
||||
case ALLEGRO_KEY_U: return ImGuiKey_U;
|
||||
case ALLEGRO_KEY_V: return ImGuiKey_V;
|
||||
case ALLEGRO_KEY_W: return ImGuiKey_W;
|
||||
case ALLEGRO_KEY_X: return ImGuiKey_X;
|
||||
case ALLEGRO_KEY_Y: return ImGuiKey_Y;
|
||||
case ALLEGRO_KEY_Z: return ImGuiKey_Z;
|
||||
case ALLEGRO_KEY_F1: return ImGuiKey_F1;
|
||||
case ALLEGRO_KEY_F2: return ImGuiKey_F2;
|
||||
case ALLEGRO_KEY_F3: return ImGuiKey_F3;
|
||||
case ALLEGRO_KEY_F4: return ImGuiKey_F4;
|
||||
case ALLEGRO_KEY_F5: return ImGuiKey_F5;
|
||||
case ALLEGRO_KEY_F6: return ImGuiKey_F6;
|
||||
case ALLEGRO_KEY_F7: return ImGuiKey_F7;
|
||||
case ALLEGRO_KEY_F8: return ImGuiKey_F8;
|
||||
case ALLEGRO_KEY_F9: return ImGuiKey_F9;
|
||||
case ALLEGRO_KEY_F10: return ImGuiKey_F10;
|
||||
case ALLEGRO_KEY_F11: return ImGuiKey_F11;
|
||||
case ALLEGRO_KEY_F12: return ImGuiKey_F12;
|
||||
default: return ImGuiKey_None;
|
||||
}
|
||||
}
|
||||
|
||||
bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplAllegro5_Data* bd = IM_NEW(ImGui_ImplAllegro5_Data)();
|
||||
io.BackendPlatformUserData = (void*)bd;
|
||||
io.BackendPlatformName = io.BackendRendererName = "imgui_impl_allegro5";
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
|
||||
bd->Display = display;
|
||||
bd->LastCursor = ALLEGRO_SYSTEM_MOUSE_CURSOR_NONE;
|
||||
|
||||
// Create custom vertex declaration.
|
||||
// Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 floats.
|
||||
// We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion.
|
||||
ALLEGRO_VERTEX_ELEMENT elems[] =
|
||||
{
|
||||
{ ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, pos) },
|
||||
{ ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, uv) },
|
||||
{ ALLEGRO_PRIM_COLOR_ATTR, 0, offsetof(ImDrawVertAllegro, col) },
|
||||
{ 0, 0, 0 }
|
||||
};
|
||||
bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro));
|
||||
|
||||
#if ALLEGRO_HAS_CLIPBOARD
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
platform_io.Platform_SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText;
|
||||
platform_io.Platform_GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText;
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplAllegro5_Shutdown()
|
||||
{
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
ImGui_ImplAllegro5_InvalidateDeviceObjects();
|
||||
if (bd->VertexDecl)
|
||||
al_destroy_vertex_decl(bd->VertexDecl);
|
||||
if (bd->ClipboardTextData)
|
||||
al_free(bd->ClipboardTextData);
|
||||
|
||||
io.BackendPlatformName = io.BackendRendererName = nullptr;
|
||||
io.BackendPlatformUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_RendererHasTextures);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
// ev->keyboard.modifiers seems always zero so using that...
|
||||
static void ImGui_ImplAllegro5_UpdateKeyModifiers()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ALLEGRO_KEYBOARD_STATE keys;
|
||||
al_get_keyboard_state(&keys);
|
||||
io.AddKeyEvent(ImGuiMod_Ctrl, al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL));
|
||||
io.AddKeyEvent(ImGuiMod_Shift, al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT));
|
||||
io.AddKeyEvent(ImGuiMod_Alt, al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR));
|
||||
io.AddKeyEvent(ImGuiMod_Super, al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN));
|
||||
}
|
||||
|
||||
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
|
||||
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
|
||||
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
|
||||
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
|
||||
bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev)
|
||||
{
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
switch (ev->type)
|
||||
{
|
||||
case ALLEGRO_EVENT_MOUSE_AXES:
|
||||
if (ev->mouse.display == bd->Display)
|
||||
{
|
||||
io.AddMousePosEvent(ev->mouse.x, ev->mouse.y);
|
||||
io.AddMouseWheelEvent(-ev->mouse.dw, ev->mouse.dz);
|
||||
}
|
||||
return true;
|
||||
case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
|
||||
case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
|
||||
if (ev->mouse.display == bd->Display && ev->mouse.button > 0 && ev->mouse.button <= 5)
|
||||
io.AddMouseButtonEvent(ev->mouse.button - 1, ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN);
|
||||
return true;
|
||||
case ALLEGRO_EVENT_TOUCH_MOVE:
|
||||
if (ev->touch.display == bd->Display)
|
||||
io.AddMousePosEvent(ev->touch.x, ev->touch.y);
|
||||
return true;
|
||||
case ALLEGRO_EVENT_TOUCH_BEGIN:
|
||||
case ALLEGRO_EVENT_TOUCH_END:
|
||||
case ALLEGRO_EVENT_TOUCH_CANCEL:
|
||||
if (ev->touch.display == bd->Display && ev->touch.primary)
|
||||
io.AddMouseButtonEvent(0, ev->type == ALLEGRO_EVENT_TOUCH_BEGIN);
|
||||
return true;
|
||||
case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
|
||||
if (ev->mouse.display == bd->Display)
|
||||
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
|
||||
return true;
|
||||
case ALLEGRO_EVENT_KEY_CHAR:
|
||||
if (ev->keyboard.display == bd->Display)
|
||||
if (ev->keyboard.unichar != 0)
|
||||
io.AddInputCharacter((unsigned int)ev->keyboard.unichar);
|
||||
return true;
|
||||
case ALLEGRO_EVENT_KEY_DOWN:
|
||||
case ALLEGRO_EVENT_KEY_UP:
|
||||
if (ev->keyboard.display == bd->Display)
|
||||
{
|
||||
ImGui_ImplAllegro5_UpdateKeyModifiers();
|
||||
ImGuiKey key = ImGui_ImplAllegro5_KeyCodeToImGuiKey(ev->keyboard.keycode);
|
||||
io.AddKeyEvent(key, (ev->type == ALLEGRO_EVENT_KEY_DOWN));
|
||||
io.SetKeyEventNativeData(key, ev->keyboard.keycode, -1); // To support legacy indexing (<1.87 user code)
|
||||
}
|
||||
return true;
|
||||
case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT:
|
||||
if (ev->display.source == bd->Display)
|
||||
io.AddFocusEvent(false);
|
||||
return true;
|
||||
case ALLEGRO_EVENT_DISPLAY_SWITCH_IN:
|
||||
if (ev->display.source == bd->Display)
|
||||
{
|
||||
io.AddFocusEvent(true);
|
||||
#if defined(ALLEGRO_UNSTABLE)
|
||||
al_clear_keyboard_state(bd->Display);
|
||||
#endif
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void ImGui_ImplAllegro5_UpdateMouseCursor()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
|
||||
return;
|
||||
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
|
||||
|
||||
// Hide OS mouse cursor if imgui is drawing it
|
||||
if (io.MouseDrawCursor)
|
||||
imgui_cursor = ImGuiMouseCursor_None;
|
||||
|
||||
if (bd->LastCursor == imgui_cursor)
|
||||
return;
|
||||
bd->LastCursor = imgui_cursor;
|
||||
if (imgui_cursor == ImGuiMouseCursor_None)
|
||||
{
|
||||
al_set_mouse_cursor(bd->Display, bd->MouseCursorInvisible);
|
||||
}
|
||||
else
|
||||
{
|
||||
ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT;
|
||||
switch (imgui_cursor)
|
||||
{
|
||||
case ImGuiMouseCursor_TextInput: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break;
|
||||
case ImGuiMouseCursor_ResizeAll: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break;
|
||||
case ImGuiMouseCursor_ResizeNS: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break;
|
||||
case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break;
|
||||
case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break;
|
||||
case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break;
|
||||
case ImGuiMouseCursor_Wait: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY; break;
|
||||
case ImGuiMouseCursor_Progress: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_PROGRESS; break;
|
||||
case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break;
|
||||
}
|
||||
al_set_system_mouse_cursor(bd->Display, cursor_id);
|
||||
}
|
||||
}
|
||||
|
||||
void ImGui_ImplAllegro5_NewFrame()
|
||||
{
|
||||
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
|
||||
|
||||
if (!bd->MouseCursorInvisible)
|
||||
ImGui_ImplAllegro5_CreateDeviceObjects();
|
||||
|
||||
// Setup display size (every frame to accommodate for window resizing)
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
int w, h;
|
||||
w = al_get_display_width(bd->Display);
|
||||
h = al_get_display_height(bd->Display);
|
||||
io.DisplaySize = ImVec2((float)w, (float)h);
|
||||
|
||||
// Setup time step
|
||||
double current_time = al_get_time();
|
||||
io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
|
||||
bd->Time = current_time;
|
||||
|
||||
// Setup mouse cursor shape
|
||||
ImGui_ImplAllegro5_UpdateMouseCursor();
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,43 +0,0 @@
|
||||
// dear imgui: Renderer + Platform Backend for Allegro 5
|
||||
// (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Clipboard support (from Allegro 5.1.12).
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// Missing features or Issues:
|
||||
// [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually.
|
||||
// [ ] Platform: Missing gamepad support.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
struct ALLEGRO_DISPLAY;
|
||||
union ALLEGRO_EVENT;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display);
|
||||
IMGUI_IMPL_API void ImGui_ImplAllegro5_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplAllegro5_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data);
|
||||
IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event);
|
||||
|
||||
// Use if you want to reset your rendering device without losing Dear ImGui state.
|
||||
IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,308 +0,0 @@
|
||||
// dear imgui: Platform Binding for Android native app
|
||||
// This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
|
||||
// Missing features or Issues:
|
||||
// [ ] Platform: Clipboard support.
|
||||
// [ ] Platform: Gamepad support.
|
||||
// [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
|
||||
// Important:
|
||||
// - Consider using SDL or GLFW backend on Android, which will be more full-featured than this.
|
||||
// - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
|
||||
// - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446)
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
|
||||
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
|
||||
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
|
||||
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
|
||||
// 2021-03-04: Initial version.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_android.h"
|
||||
#include <time.h>
|
||||
#include <android/native_window.h>
|
||||
#include <android/input.h>
|
||||
#include <android/keycodes.h>
|
||||
#include <android/log.h>
|
||||
|
||||
// Android data
|
||||
static double g_Time = 0.0;
|
||||
static ANativeWindow* g_Window;
|
||||
static char g_LogTag[] = "ImGuiExample";
|
||||
|
||||
static ImGuiKey ImGui_ImplAndroid_KeyCodeToImGuiKey(int32_t key_code)
|
||||
{
|
||||
switch (key_code)
|
||||
{
|
||||
case AKEYCODE_TAB: return ImGuiKey_Tab;
|
||||
case AKEYCODE_DPAD_LEFT: return ImGuiKey_LeftArrow;
|
||||
case AKEYCODE_DPAD_RIGHT: return ImGuiKey_RightArrow;
|
||||
case AKEYCODE_DPAD_UP: return ImGuiKey_UpArrow;
|
||||
case AKEYCODE_DPAD_DOWN: return ImGuiKey_DownArrow;
|
||||
case AKEYCODE_PAGE_UP: return ImGuiKey_PageUp;
|
||||
case AKEYCODE_PAGE_DOWN: return ImGuiKey_PageDown;
|
||||
case AKEYCODE_MOVE_HOME: return ImGuiKey_Home;
|
||||
case AKEYCODE_MOVE_END: return ImGuiKey_End;
|
||||
case AKEYCODE_INSERT: return ImGuiKey_Insert;
|
||||
case AKEYCODE_FORWARD_DEL: return ImGuiKey_Delete;
|
||||
case AKEYCODE_DEL: return ImGuiKey_Backspace;
|
||||
case AKEYCODE_SPACE: return ImGuiKey_Space;
|
||||
case AKEYCODE_ENTER: return ImGuiKey_Enter;
|
||||
case AKEYCODE_ESCAPE: return ImGuiKey_Escape;
|
||||
case AKEYCODE_APOSTROPHE: return ImGuiKey_Apostrophe;
|
||||
case AKEYCODE_COMMA: return ImGuiKey_Comma;
|
||||
case AKEYCODE_MINUS: return ImGuiKey_Minus;
|
||||
case AKEYCODE_PERIOD: return ImGuiKey_Period;
|
||||
case AKEYCODE_SLASH: return ImGuiKey_Slash;
|
||||
case AKEYCODE_SEMICOLON: return ImGuiKey_Semicolon;
|
||||
case AKEYCODE_EQUALS: return ImGuiKey_Equal;
|
||||
case AKEYCODE_LEFT_BRACKET: return ImGuiKey_LeftBracket;
|
||||
case AKEYCODE_BACKSLASH: return ImGuiKey_Backslash;
|
||||
case AKEYCODE_RIGHT_BRACKET: return ImGuiKey_RightBracket;
|
||||
case AKEYCODE_GRAVE: return ImGuiKey_GraveAccent;
|
||||
case AKEYCODE_CAPS_LOCK: return ImGuiKey_CapsLock;
|
||||
case AKEYCODE_SCROLL_LOCK: return ImGuiKey_ScrollLock;
|
||||
case AKEYCODE_NUM_LOCK: return ImGuiKey_NumLock;
|
||||
case AKEYCODE_SYSRQ: return ImGuiKey_PrintScreen;
|
||||
case AKEYCODE_BREAK: return ImGuiKey_Pause;
|
||||
case AKEYCODE_NUMPAD_0: return ImGuiKey_Keypad0;
|
||||
case AKEYCODE_NUMPAD_1: return ImGuiKey_Keypad1;
|
||||
case AKEYCODE_NUMPAD_2: return ImGuiKey_Keypad2;
|
||||
case AKEYCODE_NUMPAD_3: return ImGuiKey_Keypad3;
|
||||
case AKEYCODE_NUMPAD_4: return ImGuiKey_Keypad4;
|
||||
case AKEYCODE_NUMPAD_5: return ImGuiKey_Keypad5;
|
||||
case AKEYCODE_NUMPAD_6: return ImGuiKey_Keypad6;
|
||||
case AKEYCODE_NUMPAD_7: return ImGuiKey_Keypad7;
|
||||
case AKEYCODE_NUMPAD_8: return ImGuiKey_Keypad8;
|
||||
case AKEYCODE_NUMPAD_9: return ImGuiKey_Keypad9;
|
||||
case AKEYCODE_NUMPAD_DOT: return ImGuiKey_KeypadDecimal;
|
||||
case AKEYCODE_NUMPAD_DIVIDE: return ImGuiKey_KeypadDivide;
|
||||
case AKEYCODE_NUMPAD_MULTIPLY: return ImGuiKey_KeypadMultiply;
|
||||
case AKEYCODE_NUMPAD_SUBTRACT: return ImGuiKey_KeypadSubtract;
|
||||
case AKEYCODE_NUMPAD_ADD: return ImGuiKey_KeypadAdd;
|
||||
case AKEYCODE_NUMPAD_ENTER: return ImGuiKey_KeypadEnter;
|
||||
case AKEYCODE_NUMPAD_EQUALS: return ImGuiKey_KeypadEqual;
|
||||
case AKEYCODE_CTRL_LEFT: return ImGuiKey_LeftCtrl;
|
||||
case AKEYCODE_SHIFT_LEFT: return ImGuiKey_LeftShift;
|
||||
case AKEYCODE_ALT_LEFT: return ImGuiKey_LeftAlt;
|
||||
case AKEYCODE_META_LEFT: return ImGuiKey_LeftSuper;
|
||||
case AKEYCODE_CTRL_RIGHT: return ImGuiKey_RightCtrl;
|
||||
case AKEYCODE_SHIFT_RIGHT: return ImGuiKey_RightShift;
|
||||
case AKEYCODE_ALT_RIGHT: return ImGuiKey_RightAlt;
|
||||
case AKEYCODE_META_RIGHT: return ImGuiKey_RightSuper;
|
||||
case AKEYCODE_MENU: return ImGuiKey_Menu;
|
||||
case AKEYCODE_0: return ImGuiKey_0;
|
||||
case AKEYCODE_1: return ImGuiKey_1;
|
||||
case AKEYCODE_2: return ImGuiKey_2;
|
||||
case AKEYCODE_3: return ImGuiKey_3;
|
||||
case AKEYCODE_4: return ImGuiKey_4;
|
||||
case AKEYCODE_5: return ImGuiKey_5;
|
||||
case AKEYCODE_6: return ImGuiKey_6;
|
||||
case AKEYCODE_7: return ImGuiKey_7;
|
||||
case AKEYCODE_8: return ImGuiKey_8;
|
||||
case AKEYCODE_9: return ImGuiKey_9;
|
||||
case AKEYCODE_A: return ImGuiKey_A;
|
||||
case AKEYCODE_B: return ImGuiKey_B;
|
||||
case AKEYCODE_C: return ImGuiKey_C;
|
||||
case AKEYCODE_D: return ImGuiKey_D;
|
||||
case AKEYCODE_E: return ImGuiKey_E;
|
||||
case AKEYCODE_F: return ImGuiKey_F;
|
||||
case AKEYCODE_G: return ImGuiKey_G;
|
||||
case AKEYCODE_H: return ImGuiKey_H;
|
||||
case AKEYCODE_I: return ImGuiKey_I;
|
||||
case AKEYCODE_J: return ImGuiKey_J;
|
||||
case AKEYCODE_K: return ImGuiKey_K;
|
||||
case AKEYCODE_L: return ImGuiKey_L;
|
||||
case AKEYCODE_M: return ImGuiKey_M;
|
||||
case AKEYCODE_N: return ImGuiKey_N;
|
||||
case AKEYCODE_O: return ImGuiKey_O;
|
||||
case AKEYCODE_P: return ImGuiKey_P;
|
||||
case AKEYCODE_Q: return ImGuiKey_Q;
|
||||
case AKEYCODE_R: return ImGuiKey_R;
|
||||
case AKEYCODE_S: return ImGuiKey_S;
|
||||
case AKEYCODE_T: return ImGuiKey_T;
|
||||
case AKEYCODE_U: return ImGuiKey_U;
|
||||
case AKEYCODE_V: return ImGuiKey_V;
|
||||
case AKEYCODE_W: return ImGuiKey_W;
|
||||
case AKEYCODE_X: return ImGuiKey_X;
|
||||
case AKEYCODE_Y: return ImGuiKey_Y;
|
||||
case AKEYCODE_Z: return ImGuiKey_Z;
|
||||
case AKEYCODE_F1: return ImGuiKey_F1;
|
||||
case AKEYCODE_F2: return ImGuiKey_F2;
|
||||
case AKEYCODE_F3: return ImGuiKey_F3;
|
||||
case AKEYCODE_F4: return ImGuiKey_F4;
|
||||
case AKEYCODE_F5: return ImGuiKey_F5;
|
||||
case AKEYCODE_F6: return ImGuiKey_F6;
|
||||
case AKEYCODE_F7: return ImGuiKey_F7;
|
||||
case AKEYCODE_F8: return ImGuiKey_F8;
|
||||
case AKEYCODE_F9: return ImGuiKey_F9;
|
||||
case AKEYCODE_F10: return ImGuiKey_F10;
|
||||
case AKEYCODE_F11: return ImGuiKey_F11;
|
||||
case AKEYCODE_F12: return ImGuiKey_F12;
|
||||
default: return ImGuiKey_None;
|
||||
}
|
||||
}
|
||||
|
||||
int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
int32_t event_type = AInputEvent_getType(input_event);
|
||||
switch (event_type)
|
||||
{
|
||||
case AINPUT_EVENT_TYPE_KEY:
|
||||
{
|
||||
int32_t event_key_code = AKeyEvent_getKeyCode(input_event);
|
||||
int32_t event_scan_code = AKeyEvent_getScanCode(input_event);
|
||||
int32_t event_action = AKeyEvent_getAction(input_event);
|
||||
int32_t event_meta_state = AKeyEvent_getMetaState(input_event);
|
||||
|
||||
io.AddKeyEvent(ImGuiMod_Ctrl, (event_meta_state & AMETA_CTRL_ON) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Shift, (event_meta_state & AMETA_SHIFT_ON) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Alt, (event_meta_state & AMETA_ALT_ON) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Super, (event_meta_state & AMETA_META_ON) != 0);
|
||||
|
||||
switch (event_action)
|
||||
{
|
||||
// FIXME: AKEY_EVENT_ACTION_DOWN and AKEY_EVENT_ACTION_UP occur at once as soon as a touch pointer
|
||||
// goes up from a key. We use a simple key event queue/ and process one event per key per frame in
|
||||
// ImGui_ImplAndroid_NewFrame()...or consider using IO queue, if suitable: https://github.com/ocornut/imgui/issues/2787
|
||||
case AKEY_EVENT_ACTION_DOWN:
|
||||
case AKEY_EVENT_ACTION_UP:
|
||||
{
|
||||
ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code);
|
||||
if (key != ImGuiKey_None)
|
||||
{
|
||||
io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN);
|
||||
io.SetKeyEventNativeData(key, event_key_code, event_scan_code);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case AINPUT_EVENT_TYPE_MOTION:
|
||||
{
|
||||
int32_t event_action = AMotionEvent_getAction(input_event);
|
||||
int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
|
||||
event_action &= AMOTION_EVENT_ACTION_MASK;
|
||||
|
||||
switch (AMotionEvent_getToolType(input_event, event_pointer_index))
|
||||
{
|
||||
case AMOTION_EVENT_TOOL_TYPE_MOUSE:
|
||||
io.AddMouseSourceEvent(ImGuiMouseSource_Mouse);
|
||||
break;
|
||||
case AMOTION_EVENT_TOOL_TYPE_STYLUS:
|
||||
case AMOTION_EVENT_TOOL_TYPE_ERASER:
|
||||
io.AddMouseSourceEvent(ImGuiMouseSource_Pen);
|
||||
break;
|
||||
case AMOTION_EVENT_TOOL_TYPE_FINGER:
|
||||
default:
|
||||
io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen);
|
||||
break;
|
||||
}
|
||||
|
||||
switch (event_action)
|
||||
{
|
||||
case AMOTION_EVENT_ACTION_DOWN:
|
||||
case AMOTION_EVENT_ACTION_UP:
|
||||
{
|
||||
// Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP,
|
||||
// but we have to process them separately to identify the actual button pressed. This is done below via
|
||||
// AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback).
|
||||
int tool_type = AMotionEvent_getToolType(input_event, event_pointer_index);
|
||||
if (tool_type == AMOTION_EVENT_TOOL_TYPE_FINGER || tool_type == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)
|
||||
{
|
||||
io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
|
||||
io.AddMouseButtonEvent(0, event_action == AMOTION_EVENT_ACTION_DOWN);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case AMOTION_EVENT_ACTION_BUTTON_PRESS:
|
||||
case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
|
||||
{
|
||||
int32_t button_state = AMotionEvent_getButtonState(input_event);
|
||||
io.AddMouseButtonEvent(0, (button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0);
|
||||
io.AddMouseButtonEvent(1, (button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0);
|
||||
io.AddMouseButtonEvent(2, (button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0);
|
||||
break;
|
||||
}
|
||||
case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse)
|
||||
case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN
|
||||
io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
|
||||
break;
|
||||
case AMOTION_EVENT_ACTION_SCROLL:
|
||||
io.AddMouseWheelEvent(AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_HSCROLL, event_pointer_index), AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_VSCROLL, event_pointer_index));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool ImGui_ImplAndroid_Init(ANativeWindow* window)
|
||||
{
|
||||
IMGUI_CHECKVERSION();
|
||||
|
||||
g_Window = window;
|
||||
g_Time = 0.0;
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendPlatformName = "imgui_impl_android";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplAndroid_Shutdown()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendPlatformName = nullptr;
|
||||
}
|
||||
|
||||
void ImGui_ImplAndroid_NewFrame()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Setup display size (every frame to accommodate for window resizing)
|
||||
int32_t window_width = ANativeWindow_getWidth(g_Window);
|
||||
int32_t window_height = ANativeWindow_getHeight(g_Window);
|
||||
int display_width = window_width;
|
||||
int display_height = window_height;
|
||||
|
||||
io.DisplaySize = ImVec2((float)window_width, (float)window_height);
|
||||
if (window_width > 0 && window_height > 0)
|
||||
io.DisplayFramebufferScale = ImVec2((float)display_width / window_width, (float)display_height / window_height);
|
||||
|
||||
// Setup time step
|
||||
struct timespec current_timespec;
|
||||
clock_gettime(CLOCK_MONOTONIC, ¤t_timespec);
|
||||
double current_time = (double)(current_timespec.tv_sec) + (current_timespec.tv_nsec / 1000000000.0);
|
||||
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
|
||||
g_Time = current_time;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,37 +0,0 @@
|
||||
// dear imgui: Platform Binding for Android native app
|
||||
// This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
|
||||
// Missing features or Issues:
|
||||
// [ ] Platform: Clipboard support.
|
||||
// [ ] Platform: Gamepad support.
|
||||
// [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
|
||||
// Important:
|
||||
// - Consider using SDL or GLFW backend on Android, which will be more full-featured than this.
|
||||
// - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
|
||||
// - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446)
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
struct ANativeWindow;
|
||||
struct AInputEvent;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window);
|
||||
IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event);
|
||||
IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame();
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
657
source/thirdparty/imgui/backends/imgui_impl_dx10.cpp
vendored
657
source/thirdparty/imgui/backends/imgui_impl_dx10.cpp
vendored
@@ -1,657 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX10
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-11: DirectX10: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
|
||||
// 2025-05-07: DirectX10: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
|
||||
// 2025-01-06: DirectX10: Expose selected render state in ImGui_ImplDX10_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
|
||||
// 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap.
|
||||
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-05-19: DirectX10: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-02-18: DirectX10: Change blending equation to preserve alpha in output buffer.
|
||||
// 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData().
|
||||
// 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
|
||||
// 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions.
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the old combined DX10+Win32 example.
|
||||
// 2018-06-08: DirectX10: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
|
||||
// 2018-04-09: Misc: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) on other backends.
|
||||
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself.
|
||||
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
|
||||
// 2016-05-07: DirectX10: Disabling depth-write.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_dx10.h"
|
||||
|
||||
// DirectX
|
||||
#include <stdio.h>
|
||||
#include <d3d10_1.h>
|
||||
#include <d3d10.h>
|
||||
#include <d3dcompiler.h>
|
||||
#ifdef _MSC_VER
|
||||
#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
|
||||
#endif
|
||||
|
||||
// Clang/GCC warnings with -Weverything
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
|
||||
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
|
||||
#endif
|
||||
|
||||
// DirectX10 data
|
||||
struct ImGui_ImplDX10_Texture
|
||||
{
|
||||
ID3D10Texture2D* pTexture;
|
||||
ID3D10ShaderResourceView* pTextureView;
|
||||
};
|
||||
|
||||
struct ImGui_ImplDX10_Data
|
||||
{
|
||||
ID3D10Device* pd3dDevice;
|
||||
IDXGIFactory* pFactory;
|
||||
ID3D10Buffer* pVB;
|
||||
ID3D10Buffer* pIB;
|
||||
ID3D10VertexShader* pVertexShader;
|
||||
ID3D10InputLayout* pInputLayout;
|
||||
ID3D10Buffer* pVertexConstantBuffer;
|
||||
ID3D10PixelShader* pPixelShader;
|
||||
ID3D10SamplerState* pFontSampler;
|
||||
ID3D10RasterizerState* pRasterizerState;
|
||||
ID3D10BlendState* pBlendState;
|
||||
ID3D10DepthStencilState* pDepthStencilState;
|
||||
int VertexBufferSize;
|
||||
int IndexBufferSize;
|
||||
|
||||
ImGui_ImplDX10_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
|
||||
};
|
||||
|
||||
struct VERTEX_CONSTANT_BUFFER_DX10
|
||||
{
|
||||
float mvp[4][4];
|
||||
};
|
||||
|
||||
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
|
||||
}
|
||||
|
||||
// Functions
|
||||
static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device)
|
||||
{
|
||||
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
|
||||
|
||||
// Setup viewport
|
||||
D3D10_VIEWPORT vp = {};
|
||||
vp.Width = (UINT)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
|
||||
vp.Height = (UINT)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
|
||||
vp.MinDepth = 0.0f;
|
||||
vp.MaxDepth = 1.0f;
|
||||
vp.TopLeftX = vp.TopLeftY = 0;
|
||||
device->RSSetViewports(1, &vp);
|
||||
|
||||
// Setup orthographic projection matrix into our constant buffer
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
|
||||
void* mapped_resource;
|
||||
if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK)
|
||||
{
|
||||
VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource;
|
||||
float L = draw_data->DisplayPos.x;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
|
||||
float T = draw_data->DisplayPos.y;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
|
||||
float mvp[4][4] =
|
||||
{
|
||||
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 0.5f, 0.0f },
|
||||
{ (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
|
||||
};
|
||||
memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
|
||||
bd->pVertexConstantBuffer->Unmap();
|
||||
}
|
||||
|
||||
// Setup shader and vertex buffers
|
||||
unsigned int stride = sizeof(ImDrawVert);
|
||||
unsigned int offset = 0;
|
||||
device->IASetInputLayout(bd->pInputLayout);
|
||||
device->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
|
||||
device->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
|
||||
device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
device->VSSetShader(bd->pVertexShader);
|
||||
device->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
|
||||
device->PSSetShader(bd->pPixelShader);
|
||||
device->PSSetSamplers(0, 1, &bd->pFontSampler);
|
||||
device->GSSetShader(nullptr);
|
||||
|
||||
// Setup render state
|
||||
const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
|
||||
device->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
|
||||
device->OMSetDepthStencilState(bd->pDepthStencilState, 0);
|
||||
device->RSSetState(bd->pRasterizerState);
|
||||
}
|
||||
|
||||
// Render function
|
||||
void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
|
||||
ID3D10Device* device = bd->pd3dDevice;
|
||||
|
||||
// Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
|
||||
// (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
|
||||
if (draw_data->Textures != nullptr)
|
||||
for (ImTextureData* tex : *draw_data->Textures)
|
||||
if (tex->Status != ImTextureStatus_OK)
|
||||
ImGui_ImplDX10_UpdateTexture(tex);
|
||||
|
||||
// Create and grow vertex/index buffers if needed
|
||||
if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
|
||||
{
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
|
||||
bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
|
||||
D3D10_BUFFER_DESC desc = {};
|
||||
desc.Usage = D3D10_USAGE_DYNAMIC;
|
||||
desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
|
||||
desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
|
||||
desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
|
||||
desc.MiscFlags = 0;
|
||||
if (device->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
|
||||
return;
|
||||
}
|
||||
|
||||
if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
|
||||
{
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
|
||||
bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
|
||||
D3D10_BUFFER_DESC desc = {};
|
||||
desc.Usage = D3D10_USAGE_DYNAMIC;
|
||||
desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
|
||||
desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
|
||||
desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
|
||||
if (device->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
|
||||
return;
|
||||
}
|
||||
|
||||
// Copy and convert all vertices into a single contiguous buffer
|
||||
ImDrawVert* vtx_dst = nullptr;
|
||||
ImDrawIdx* idx_dst = nullptr;
|
||||
bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
|
||||
bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
|
||||
memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
vtx_dst += draw_list->VtxBuffer.Size;
|
||||
idx_dst += draw_list->IdxBuffer.Size;
|
||||
}
|
||||
bd->pVB->Unmap();
|
||||
bd->pIB->Unmap();
|
||||
|
||||
// Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
|
||||
struct BACKUP_DX10_STATE
|
||||
{
|
||||
UINT ScissorRectsCount, ViewportsCount;
|
||||
D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
|
||||
D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
|
||||
ID3D10RasterizerState* RS;
|
||||
ID3D10BlendState* BlendState;
|
||||
FLOAT BlendFactor[4];
|
||||
UINT SampleMask;
|
||||
UINT StencilRef;
|
||||
ID3D10DepthStencilState* DepthStencilState;
|
||||
ID3D10ShaderResourceView* PSShaderResource;
|
||||
ID3D10SamplerState* PSSampler;
|
||||
ID3D10PixelShader* PS;
|
||||
ID3D10VertexShader* VS;
|
||||
ID3D10GeometryShader* GS;
|
||||
D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
|
||||
ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
|
||||
UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
|
||||
DXGI_FORMAT IndexBufferFormat;
|
||||
ID3D10InputLayout* InputLayout;
|
||||
};
|
||||
BACKUP_DX10_STATE old = {};
|
||||
old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
|
||||
device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
|
||||
device->RSGetViewports(&old.ViewportsCount, old.Viewports);
|
||||
device->RSGetState(&old.RS);
|
||||
device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
|
||||
device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
|
||||
device->PSGetShaderResources(0, 1, &old.PSShaderResource);
|
||||
device->PSGetSamplers(0, 1, &old.PSSampler);
|
||||
device->PSGetShader(&old.PS);
|
||||
device->VSGetShader(&old.VS);
|
||||
device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
|
||||
device->GSGetShader(&old.GS);
|
||||
device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
|
||||
device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
|
||||
device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
|
||||
device->IAGetInputLayout(&old.InputLayout);
|
||||
|
||||
// Setup desired DX state
|
||||
ImGui_ImplDX10_SetupRenderState(draw_data, device);
|
||||
// Setup render state structure (for callbacks and custom texture bindings)
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
ImGui_ImplDX10_RenderState render_state;
|
||||
render_state.Device = bd->pd3dDevice;
|
||||
render_state.SamplerDefault = bd->pFontSampler;
|
||||
render_state.VertexConstantBuffer = bd->pVertexConstantBuffer;
|
||||
platform_io.Renderer_RenderState = &render_state;
|
||||
|
||||
// Render command lists
|
||||
// (Because we merged all buffers into a single one, we maintain our own offset into them)
|
||||
int global_vtx_offset = 0;
|
||||
int global_idx_offset = 0;
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
ImVec2 clip_scale = draw_data->FramebufferScale;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback != nullptr)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplDX10_SetupRenderState(draw_data, device);
|
||||
else
|
||||
pcmd->UserCallback(draw_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
|
||||
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
|
||||
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle
|
||||
const D3D10_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
|
||||
device->RSSetScissorRects(1, &r);
|
||||
|
||||
// Bind texture, Draw
|
||||
ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->GetTexID();
|
||||
device->PSSetShaderResources(0, 1, &texture_srv);
|
||||
device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
|
||||
}
|
||||
}
|
||||
global_idx_offset += draw_list->IdxBuffer.Size;
|
||||
global_vtx_offset += draw_list->VtxBuffer.Size;
|
||||
}
|
||||
platform_io.Renderer_RenderState = nullptr;
|
||||
|
||||
// Restore modified DX state
|
||||
device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
|
||||
device->RSSetViewports(old.ViewportsCount, old.Viewports);
|
||||
device->RSSetState(old.RS); if (old.RS) old.RS->Release();
|
||||
device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
|
||||
device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
|
||||
device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
|
||||
device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
|
||||
device->PSSetShader(old.PS); if (old.PS) old.PS->Release();
|
||||
device->VSSetShader(old.VS); if (old.VS) old.VS->Release();
|
||||
device->GSSetShader(old.GS); if (old.GS) old.GS->Release();
|
||||
device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
|
||||
device->IASetPrimitiveTopology(old.PrimitiveTopology);
|
||||
device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
|
||||
device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
|
||||
device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX10_DestroyTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData;
|
||||
if (backend_tex == nullptr)
|
||||
return;
|
||||
IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID);
|
||||
backend_tex->pTexture->Release();
|
||||
backend_tex->pTextureView->Release();
|
||||
IM_DELETE(backend_tex);
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex->SetTexID(ImTextureID_Invalid);
|
||||
tex->SetStatus(ImTextureStatus_Destroyed);
|
||||
tex->BackendUserData = nullptr;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
|
||||
if (tex->Status == ImTextureStatus_WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
|
||||
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
unsigned int* pixels = (unsigned int*)tex->GetPixels();
|
||||
ImGui_ImplDX10_Texture* backend_tex = IM_NEW(ImGui_ImplDX10_Texture)();
|
||||
|
||||
// Create texture
|
||||
D3D10_TEXTURE2D_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.Width = (UINT)tex->Width;
|
||||
desc.Height = (UINT)tex->Height;
|
||||
desc.MipLevels = 1;
|
||||
desc.ArraySize = 1;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Usage = D3D10_USAGE_DEFAULT;
|
||||
desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
|
||||
desc.CPUAccessFlags = 0;
|
||||
|
||||
D3D10_SUBRESOURCE_DATA subResource;
|
||||
subResource.pSysMem = pixels;
|
||||
subResource.SysMemPitch = desc.Width * 4;
|
||||
subResource.SysMemSlicePitch = 0;
|
||||
bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &backend_tex->pTexture);
|
||||
IM_ASSERT(backend_tex->pTexture != nullptr && "Backend failed to create texture!");
|
||||
|
||||
// Create texture view
|
||||
D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
|
||||
ZeroMemory(&srv_desc, sizeof(srv_desc));
|
||||
srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
|
||||
srv_desc.Texture2D.MipLevels = desc.MipLevels;
|
||||
srv_desc.Texture2D.MostDetailedMip = 0;
|
||||
bd->pd3dDevice->CreateShaderResourceView(backend_tex->pTexture, &srv_desc, &backend_tex->pTextureView);
|
||||
IM_ASSERT(backend_tex->pTextureView != nullptr && "Backend failed to create texture!");
|
||||
|
||||
// Store identifiers
|
||||
tex->SetTexID((ImTextureID)(intptr_t)backend_tex->pTextureView);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
tex->BackendUserData = backend_tex;
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantUpdates)
|
||||
{
|
||||
// Update selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
|
||||
ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData;
|
||||
IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID);
|
||||
for (ImTextureRect& r : tex->Updates)
|
||||
{
|
||||
D3D10_BOX box = { (UINT)r.x, (UINT)r.y, (UINT)0, (UINT)(r.x + r.w), (UINT)(r.y + r.h), (UINT)1 };
|
||||
bd->pd3dDevice->UpdateSubresource(backend_tex->pTexture, 0, &box, tex->GetPixelsAt(r.x, r.y), (UINT)tex->GetPitch(), 0);
|
||||
}
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
|
||||
ImGui_ImplDX10_DestroyTexture(tex);
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX10_CreateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
|
||||
if (!bd->pd3dDevice)
|
||||
return false;
|
||||
ImGui_ImplDX10_InvalidateDeviceObjects();
|
||||
|
||||
// By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
|
||||
// If you would like to use this DX10 sample code but remove this dependency you can:
|
||||
// 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
|
||||
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
|
||||
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
|
||||
|
||||
// Create the vertex shader
|
||||
{
|
||||
static const char* vertexShader =
|
||||
"cbuffer vertexBuffer : register(b0) \
|
||||
{\
|
||||
float4x4 ProjectionMatrix; \
|
||||
};\
|
||||
struct VS_INPUT\
|
||||
{\
|
||||
float2 pos : POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
PS_INPUT main(VS_INPUT input)\
|
||||
{\
|
||||
PS_INPUT output;\
|
||||
output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
|
||||
output.col = input.col;\
|
||||
output.uv = input.uv;\
|
||||
return output;\
|
||||
}";
|
||||
|
||||
ID3DBlob* vertexShaderBlob;
|
||||
if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
|
||||
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pVertexShader) != S_OK)
|
||||
{
|
||||
vertexShaderBlob->Release();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create the input layout
|
||||
D3D10_INPUT_ELEMENT_DESC local_layout[] =
|
||||
{
|
||||
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
|
||||
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
|
||||
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
|
||||
};
|
||||
if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
|
||||
{
|
||||
vertexShaderBlob->Release();
|
||||
return false;
|
||||
}
|
||||
vertexShaderBlob->Release();
|
||||
|
||||
// Create the constant buffer
|
||||
{
|
||||
D3D10_BUFFER_DESC desc = {};
|
||||
desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10);
|
||||
desc.Usage = D3D10_USAGE_DYNAMIC;
|
||||
desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
|
||||
desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
|
||||
desc.MiscFlags = 0;
|
||||
bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
// Create the pixel shader
|
||||
{
|
||||
static const char* pixelShader =
|
||||
"struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
sampler sampler0;\
|
||||
Texture2D texture0;\
|
||||
\
|
||||
float4 main(PS_INPUT input) : SV_Target\
|
||||
{\
|
||||
float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
|
||||
return out_col; \
|
||||
}";
|
||||
|
||||
ID3DBlob* pixelShaderBlob;
|
||||
if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
|
||||
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &bd->pPixelShader) != S_OK)
|
||||
{
|
||||
pixelShaderBlob->Release();
|
||||
return false;
|
||||
}
|
||||
pixelShaderBlob->Release();
|
||||
}
|
||||
|
||||
// Create the blending setup
|
||||
{
|
||||
D3D10_BLEND_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.AlphaToCoverageEnable = false;
|
||||
desc.BlendEnable[0] = true;
|
||||
desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
|
||||
desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
|
||||
desc.BlendOp = D3D10_BLEND_OP_ADD;
|
||||
desc.SrcBlendAlpha = D3D10_BLEND_ONE;
|
||||
desc.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
|
||||
desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
|
||||
desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
|
||||
bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
|
||||
}
|
||||
|
||||
// Create the rasterizer state
|
||||
{
|
||||
D3D10_RASTERIZER_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.FillMode = D3D10_FILL_SOLID;
|
||||
desc.CullMode = D3D10_CULL_NONE;
|
||||
desc.ScissorEnable = true;
|
||||
desc.DepthClipEnable = true;
|
||||
bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
|
||||
}
|
||||
|
||||
// Create depth-stencil State
|
||||
{
|
||||
D3D10_DEPTH_STENCIL_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.DepthEnable = false;
|
||||
desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
|
||||
desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
|
||||
desc.StencilEnable = false;
|
||||
desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
|
||||
desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
|
||||
desc.BackFace = desc.FrontFace;
|
||||
bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
|
||||
}
|
||||
|
||||
// Create texture sampler
|
||||
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
|
||||
{
|
||||
D3D10_SAMPLER_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
|
||||
desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
|
||||
desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
|
||||
desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
|
||||
desc.MipLODBias = 0.f;
|
||||
desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
|
||||
desc.MinLOD = 0.f;
|
||||
desc.MaxLOD = 0.f;
|
||||
bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX10_InvalidateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
|
||||
if (!bd->pd3dDevice)
|
||||
return;
|
||||
|
||||
// Destroy all textures
|
||||
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
|
||||
if (tex->RefCount == 1)
|
||||
ImGui_ImplDX10_DestroyTexture(tex);
|
||||
if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
|
||||
if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
|
||||
if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
|
||||
if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
|
||||
if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
|
||||
if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
|
||||
if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
|
||||
if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX10_Init(ID3D10Device* device)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplDX10_Data* bd = IM_NEW(ImGui_ImplDX10_Data)();
|
||||
io.BackendRendererUserData = (void*)bd;
|
||||
io.BackendRendererName = "imgui_impl_dx10";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
|
||||
|
||||
// Get factory from device
|
||||
IDXGIDevice* pDXGIDevice = nullptr;
|
||||
IDXGIAdapter* pDXGIAdapter = nullptr;
|
||||
IDXGIFactory* pFactory = nullptr;
|
||||
if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
|
||||
if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
|
||||
if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
|
||||
{
|
||||
bd->pd3dDevice = device;
|
||||
bd->pFactory = pFactory;
|
||||
}
|
||||
if (pDXGIDevice) pDXGIDevice->Release();
|
||||
if (pDXGIAdapter) pDXGIAdapter->Release();
|
||||
bd->pd3dDevice->AddRef();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX10_Shutdown()
|
||||
{
|
||||
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
ImGui_ImplDX10_InvalidateDeviceObjects();
|
||||
if (bd->pFactory) { bd->pFactory->Release(); }
|
||||
if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
|
||||
io.BackendRendererName = nullptr;
|
||||
io.BackendRendererUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
void ImGui_ImplDX10_NewFrame()
|
||||
{
|
||||
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?");
|
||||
|
||||
if (!bd->pVertexShader)
|
||||
if (!ImGui_ImplDX10_CreateDeviceObjects())
|
||||
IM_ASSERT(0 && "ImGui_ImplDX10_CreateDeviceObjects() failed!");
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,48 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX10
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
struct ID3D10Device;
|
||||
struct ID3D10SamplerState;
|
||||
struct ID3D10Buffer;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX10_Init(ID3D10Device* device);
|
||||
IMGUI_IMPL_API void ImGui_ImplDX10_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX10_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data);
|
||||
|
||||
// Use if you want to reset your rendering device without losing Dear ImGui state.
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
// [BETA] Selected render state data shared with callbacks.
|
||||
// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX10_RenderDrawData() call.
|
||||
// (Please open an issue if you feel you need access to more data)
|
||||
struct ImGui_ImplDX10_RenderState
|
||||
{
|
||||
ID3D10Device* Device;
|
||||
ID3D10SamplerState* SamplerDefault;
|
||||
ID3D10Buffer* VertexConstantBuffer;
|
||||
};
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
677
source/thirdparty/imgui/backends/imgui_impl_dx11.cpp
vendored
677
source/thirdparty/imgui/backends/imgui_impl_dx11.cpp
vendored
@@ -1,677 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX11
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-11: DirectX11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
|
||||
// 2025-05-07: DirectX11: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
|
||||
// 2025-01-06: DirectX11: Expose VertexConstantBuffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handler.
|
||||
// 2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap.
|
||||
// 2024-10-07: DirectX11: Expose selected render state in ImGui_ImplDX11_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
|
||||
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer.
|
||||
// 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled).
|
||||
// 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX11_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore.
|
||||
// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
|
||||
// 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility.
|
||||
// 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
|
||||
// 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
|
||||
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
|
||||
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
|
||||
// 2016-05-07: DirectX11: Disabling depth-write.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_dx11.h"
|
||||
|
||||
// DirectX
|
||||
#include <stdio.h>
|
||||
#include <d3d11.h>
|
||||
#include <d3dcompiler.h>
|
||||
#ifdef _MSC_VER
|
||||
#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
|
||||
#endif
|
||||
|
||||
// Clang/GCC warnings with -Weverything
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
|
||||
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
|
||||
#endif
|
||||
|
||||
// DirectX11 data
|
||||
struct ImGui_ImplDX11_Texture
|
||||
{
|
||||
ID3D11Texture2D* pTexture;
|
||||
ID3D11ShaderResourceView* pTextureView;
|
||||
};
|
||||
|
||||
struct ImGui_ImplDX11_Data
|
||||
{
|
||||
ID3D11Device* pd3dDevice;
|
||||
ID3D11DeviceContext* pd3dDeviceContext;
|
||||
IDXGIFactory* pFactory;
|
||||
ID3D11Buffer* pVB;
|
||||
ID3D11Buffer* pIB;
|
||||
ID3D11VertexShader* pVertexShader;
|
||||
ID3D11InputLayout* pInputLayout;
|
||||
ID3D11Buffer* pVertexConstantBuffer;
|
||||
ID3D11PixelShader* pPixelShader;
|
||||
ID3D11SamplerState* pFontSampler;
|
||||
ID3D11RasterizerState* pRasterizerState;
|
||||
ID3D11BlendState* pBlendState;
|
||||
ID3D11DepthStencilState* pDepthStencilState;
|
||||
int VertexBufferSize;
|
||||
int IndexBufferSize;
|
||||
|
||||
ImGui_ImplDX11_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
|
||||
};
|
||||
|
||||
struct VERTEX_CONSTANT_BUFFER_DX11
|
||||
{
|
||||
float mvp[4][4];
|
||||
};
|
||||
|
||||
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
|
||||
}
|
||||
|
||||
// Functions
|
||||
static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* device_ctx)
|
||||
{
|
||||
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
|
||||
|
||||
// Setup viewport
|
||||
D3D11_VIEWPORT vp = {};
|
||||
vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
|
||||
vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
|
||||
vp.MinDepth = 0.0f;
|
||||
vp.MaxDepth = 1.0f;
|
||||
vp.TopLeftX = vp.TopLeftY = 0;
|
||||
device_ctx->RSSetViewports(1, &vp);
|
||||
|
||||
// Setup orthographic projection matrix into our constant buffer
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
|
||||
D3D11_MAPPED_SUBRESOURCE mapped_resource;
|
||||
if (device_ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK)
|
||||
{
|
||||
VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData;
|
||||
float L = draw_data->DisplayPos.x;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
|
||||
float T = draw_data->DisplayPos.y;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
|
||||
float mvp[4][4] =
|
||||
{
|
||||
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 0.5f, 0.0f },
|
||||
{ (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
|
||||
};
|
||||
memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
|
||||
device_ctx->Unmap(bd->pVertexConstantBuffer, 0);
|
||||
}
|
||||
|
||||
// Setup shader and vertex buffers
|
||||
unsigned int stride = sizeof(ImDrawVert);
|
||||
unsigned int offset = 0;
|
||||
device_ctx->IASetInputLayout(bd->pInputLayout);
|
||||
device_ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
|
||||
device_ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
|
||||
device_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
device_ctx->VSSetShader(bd->pVertexShader, nullptr, 0);
|
||||
device_ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
|
||||
device_ctx->PSSetShader(bd->pPixelShader, nullptr, 0);
|
||||
device_ctx->PSSetSamplers(0, 1, &bd->pFontSampler);
|
||||
device_ctx->GSSetShader(nullptr, nullptr, 0);
|
||||
device_ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
|
||||
device_ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
|
||||
device_ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
|
||||
|
||||
// Setup render state
|
||||
const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
|
||||
device_ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
|
||||
device_ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
|
||||
device_ctx->RSSetState(bd->pRasterizerState);
|
||||
}
|
||||
|
||||
// Render function
|
||||
void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
|
||||
ID3D11DeviceContext* device = bd->pd3dDeviceContext;
|
||||
|
||||
// Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
|
||||
// (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
|
||||
if (draw_data->Textures != nullptr)
|
||||
for (ImTextureData* tex : *draw_data->Textures)
|
||||
if (tex->Status != ImTextureStatus_OK)
|
||||
ImGui_ImplDX11_UpdateTexture(tex);
|
||||
|
||||
// Create and grow vertex/index buffers if needed
|
||||
if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
|
||||
{
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
|
||||
bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
|
||||
D3D11_BUFFER_DESC desc = {};
|
||||
desc.Usage = D3D11_USAGE_DYNAMIC;
|
||||
desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
|
||||
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
|
||||
desc.MiscFlags = 0;
|
||||
if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
|
||||
return;
|
||||
}
|
||||
if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
|
||||
{
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
|
||||
bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
|
||||
D3D11_BUFFER_DESC desc = {};
|
||||
desc.Usage = D3D11_USAGE_DYNAMIC;
|
||||
desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
|
||||
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
|
||||
if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
|
||||
return;
|
||||
}
|
||||
|
||||
// Upload vertex/index data into a single contiguous GPU buffer
|
||||
D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
|
||||
if (device->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
|
||||
return;
|
||||
if (device->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
|
||||
return;
|
||||
ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
|
||||
ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
|
||||
memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
vtx_dst += draw_list->VtxBuffer.Size;
|
||||
idx_dst += draw_list->IdxBuffer.Size;
|
||||
}
|
||||
device->Unmap(bd->pVB, 0);
|
||||
device->Unmap(bd->pIB, 0);
|
||||
|
||||
// Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
|
||||
struct BACKUP_DX11_STATE
|
||||
{
|
||||
UINT ScissorRectsCount, ViewportsCount;
|
||||
D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
|
||||
D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
|
||||
ID3D11RasterizerState* RS;
|
||||
ID3D11BlendState* BlendState;
|
||||
FLOAT BlendFactor[4];
|
||||
UINT SampleMask;
|
||||
UINT StencilRef;
|
||||
ID3D11DepthStencilState* DepthStencilState;
|
||||
ID3D11ShaderResourceView* PSShaderResource;
|
||||
ID3D11SamplerState* PSSampler;
|
||||
ID3D11PixelShader* PS;
|
||||
ID3D11VertexShader* VS;
|
||||
ID3D11GeometryShader* GS;
|
||||
UINT PSInstancesCount, VSInstancesCount, GSInstancesCount;
|
||||
ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation
|
||||
D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
|
||||
ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
|
||||
UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
|
||||
DXGI_FORMAT IndexBufferFormat;
|
||||
ID3D11InputLayout* InputLayout;
|
||||
};
|
||||
BACKUP_DX11_STATE old = {};
|
||||
old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
|
||||
device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
|
||||
device->RSGetViewports(&old.ViewportsCount, old.Viewports);
|
||||
device->RSGetState(&old.RS);
|
||||
device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
|
||||
device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
|
||||
device->PSGetShaderResources(0, 1, &old.PSShaderResource);
|
||||
device->PSGetSamplers(0, 1, &old.PSSampler);
|
||||
old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256;
|
||||
device->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
|
||||
device->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
|
||||
device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
|
||||
device->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
|
||||
|
||||
device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
|
||||
device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
|
||||
device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
|
||||
device->IAGetInputLayout(&old.InputLayout);
|
||||
|
||||
// Setup desired DX state
|
||||
ImGui_ImplDX11_SetupRenderState(draw_data, device);
|
||||
|
||||
// Setup render state structure (for callbacks and custom texture bindings)
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
ImGui_ImplDX11_RenderState render_state;
|
||||
render_state.Device = bd->pd3dDevice;
|
||||
render_state.DeviceContext = bd->pd3dDeviceContext;
|
||||
render_state.SamplerDefault = bd->pFontSampler;
|
||||
render_state.VertexConstantBuffer = bd->pVertexConstantBuffer;
|
||||
platform_io.Renderer_RenderState = &render_state;
|
||||
|
||||
// Render command lists
|
||||
// (Because we merged all buffers into a single one, we maintain our own offset into them)
|
||||
int global_idx_offset = 0;
|
||||
int global_vtx_offset = 0;
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
ImVec2 clip_scale = draw_data->FramebufferScale;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback != nullptr)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplDX11_SetupRenderState(draw_data, device);
|
||||
else
|
||||
pcmd->UserCallback(draw_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
|
||||
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
|
||||
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle
|
||||
const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
|
||||
device->RSSetScissorRects(1, &r);
|
||||
|
||||
// Bind texture, Draw
|
||||
ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID();
|
||||
device->PSSetShaderResources(0, 1, &texture_srv);
|
||||
device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
|
||||
}
|
||||
}
|
||||
global_idx_offset += draw_list->IdxBuffer.Size;
|
||||
global_vtx_offset += draw_list->VtxBuffer.Size;
|
||||
}
|
||||
platform_io.Renderer_RenderState = nullptr;
|
||||
|
||||
// Restore modified DX state
|
||||
device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
|
||||
device->RSSetViewports(old.ViewportsCount, old.Viewports);
|
||||
device->RSSetState(old.RS); if (old.RS) old.RS->Release();
|
||||
device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
|
||||
device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
|
||||
device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
|
||||
device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
|
||||
device->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
|
||||
for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
|
||||
device->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
|
||||
device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
|
||||
device->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
|
||||
for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
|
||||
device->IASetPrimitiveTopology(old.PrimitiveTopology);
|
||||
device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
|
||||
device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
|
||||
device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX11_DestroyTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData;
|
||||
if (backend_tex == nullptr)
|
||||
return;
|
||||
IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID);
|
||||
backend_tex->pTextureView->Release();
|
||||
backend_tex->pTexture->Release();
|
||||
IM_DELETE(backend_tex);
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex->SetTexID(ImTextureID_Invalid);
|
||||
tex->SetStatus(ImTextureStatus_Destroyed);
|
||||
tex->BackendUserData = nullptr;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
|
||||
if (tex->Status == ImTextureStatus_WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
|
||||
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
unsigned int* pixels = (unsigned int*)tex->GetPixels();
|
||||
ImGui_ImplDX11_Texture* backend_tex = IM_NEW(ImGui_ImplDX11_Texture)();
|
||||
|
||||
// Create texture
|
||||
D3D11_TEXTURE2D_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.Width = (UINT)tex->Width;
|
||||
desc.Height = (UINT)tex->Height;
|
||||
desc.MipLevels = 1;
|
||||
desc.ArraySize = 1;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Usage = D3D11_USAGE_DEFAULT;
|
||||
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
|
||||
desc.CPUAccessFlags = 0;
|
||||
D3D11_SUBRESOURCE_DATA subResource;
|
||||
subResource.pSysMem = pixels;
|
||||
subResource.SysMemPitch = desc.Width * 4;
|
||||
subResource.SysMemSlicePitch = 0;
|
||||
bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &backend_tex->pTexture);
|
||||
IM_ASSERT(backend_tex->pTexture != nullptr && "Backend failed to create texture!");
|
||||
|
||||
// Create texture view
|
||||
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
|
||||
ZeroMemory(&srvDesc, sizeof(srvDesc));
|
||||
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
|
||||
srvDesc.Texture2D.MipLevels = desc.MipLevels;
|
||||
srvDesc.Texture2D.MostDetailedMip = 0;
|
||||
bd->pd3dDevice->CreateShaderResourceView(backend_tex->pTexture, &srvDesc, &backend_tex->pTextureView);
|
||||
IM_ASSERT(backend_tex->pTextureView != nullptr && "Backend failed to create texture!");
|
||||
|
||||
// Store identifiers
|
||||
tex->SetTexID((ImTextureID)(intptr_t)backend_tex->pTextureView);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
tex->BackendUserData = backend_tex;
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantUpdates)
|
||||
{
|
||||
// Update selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
|
||||
ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData;
|
||||
IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID);
|
||||
for (ImTextureRect& r : tex->Updates)
|
||||
{
|
||||
D3D11_BOX box = { (UINT)r.x, (UINT)r.y, (UINT)0, (UINT)(r.x + r.w), (UINT)(r.y + r .h), (UINT)1 };
|
||||
bd->pd3dDeviceContext->UpdateSubresource(backend_tex->pTexture, 0, &box, tex->GetPixelsAt(r.x, r.y), (UINT)tex->GetPitch(), 0);
|
||||
}
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
|
||||
ImGui_ImplDX11_DestroyTexture(tex);
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX11_CreateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
|
||||
if (!bd->pd3dDevice)
|
||||
return false;
|
||||
ImGui_ImplDX11_InvalidateDeviceObjects();
|
||||
|
||||
// By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
|
||||
// If you would like to use this DX11 sample code but remove this dependency you can:
|
||||
// 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
|
||||
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
|
||||
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
|
||||
|
||||
// Create the vertex shader
|
||||
{
|
||||
static const char* vertexShader =
|
||||
"cbuffer vertexBuffer : register(b0) \
|
||||
{\
|
||||
float4x4 ProjectionMatrix; \
|
||||
};\
|
||||
struct VS_INPUT\
|
||||
{\
|
||||
float2 pos : POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
PS_INPUT main(VS_INPUT input)\
|
||||
{\
|
||||
PS_INPUT output;\
|
||||
output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
|
||||
output.col = input.col;\
|
||||
output.uv = input.uv;\
|
||||
return output;\
|
||||
}";
|
||||
|
||||
ID3DBlob* vertexShaderBlob;
|
||||
if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
|
||||
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK)
|
||||
{
|
||||
vertexShaderBlob->Release();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create the input layout
|
||||
D3D11_INPUT_ELEMENT_DESC local_layout[] =
|
||||
{
|
||||
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
|
||||
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
|
||||
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
|
||||
};
|
||||
if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
|
||||
{
|
||||
vertexShaderBlob->Release();
|
||||
return false;
|
||||
}
|
||||
vertexShaderBlob->Release();
|
||||
|
||||
// Create the constant buffer
|
||||
{
|
||||
D3D11_BUFFER_DESC desc = {};
|
||||
desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11);
|
||||
desc.Usage = D3D11_USAGE_DYNAMIC;
|
||||
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
|
||||
desc.MiscFlags = 0;
|
||||
bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
// Create the pixel shader
|
||||
{
|
||||
static const char* pixelShader =
|
||||
"struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
sampler sampler0;\
|
||||
Texture2D texture0;\
|
||||
\
|
||||
float4 main(PS_INPUT input) : SV_Target\
|
||||
{\
|
||||
float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
|
||||
return out_col; \
|
||||
}";
|
||||
|
||||
ID3DBlob* pixelShaderBlob;
|
||||
if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
|
||||
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK)
|
||||
{
|
||||
pixelShaderBlob->Release();
|
||||
return false;
|
||||
}
|
||||
pixelShaderBlob->Release();
|
||||
}
|
||||
|
||||
// Create the blending setup
|
||||
{
|
||||
D3D11_BLEND_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.AlphaToCoverageEnable = false;
|
||||
desc.RenderTarget[0].BlendEnable = true;
|
||||
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
|
||||
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
|
||||
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
|
||||
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
|
||||
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
|
||||
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
|
||||
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
|
||||
bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
|
||||
}
|
||||
|
||||
// Create the rasterizer state
|
||||
{
|
||||
D3D11_RASTERIZER_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.FillMode = D3D11_FILL_SOLID;
|
||||
desc.CullMode = D3D11_CULL_NONE;
|
||||
desc.ScissorEnable = true;
|
||||
desc.DepthClipEnable = true;
|
||||
bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
|
||||
}
|
||||
|
||||
// Create depth-stencil State
|
||||
{
|
||||
D3D11_DEPTH_STENCIL_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.DepthEnable = false;
|
||||
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
|
||||
desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
|
||||
desc.StencilEnable = false;
|
||||
desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
|
||||
desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
|
||||
desc.BackFace = desc.FrontFace;
|
||||
bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
|
||||
}
|
||||
|
||||
// Create texture sampler
|
||||
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
|
||||
{
|
||||
D3D11_SAMPLER_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
|
||||
desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
|
||||
desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
|
||||
desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
|
||||
desc.MipLODBias = 0.f;
|
||||
desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
|
||||
desc.MinLOD = 0.f;
|
||||
desc.MaxLOD = 0.f;
|
||||
bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX11_InvalidateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
|
||||
if (!bd->pd3dDevice)
|
||||
return;
|
||||
|
||||
// Destroy all textures
|
||||
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
|
||||
if (tex->RefCount == 1)
|
||||
ImGui_ImplDX11_DestroyTexture(tex);
|
||||
|
||||
if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
|
||||
if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
|
||||
if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
|
||||
if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
|
||||
if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
|
||||
if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
|
||||
if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
|
||||
if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)();
|
||||
io.BackendRendererUserData = (void*)bd;
|
||||
io.BackendRendererName = "imgui_impl_dx11";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
|
||||
|
||||
// Get factory from device
|
||||
IDXGIDevice* pDXGIDevice = nullptr;
|
||||
IDXGIAdapter* pDXGIAdapter = nullptr;
|
||||
IDXGIFactory* pFactory = nullptr;
|
||||
|
||||
if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
|
||||
if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
|
||||
if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
|
||||
{
|
||||
bd->pd3dDevice = device;
|
||||
bd->pd3dDeviceContext = device_context;
|
||||
bd->pFactory = pFactory;
|
||||
}
|
||||
if (pDXGIDevice) pDXGIDevice->Release();
|
||||
if (pDXGIAdapter) pDXGIAdapter->Release();
|
||||
bd->pd3dDevice->AddRef();
|
||||
bd->pd3dDeviceContext->AddRef();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX11_Shutdown()
|
||||
{
|
||||
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
ImGui_ImplDX11_InvalidateDeviceObjects();
|
||||
if (bd->pFactory) { bd->pFactory->Release(); }
|
||||
if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
|
||||
if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); }
|
||||
io.BackendRendererName = nullptr;
|
||||
io.BackendRendererUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
void ImGui_ImplDX11_NewFrame()
|
||||
{
|
||||
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?");
|
||||
|
||||
if (!bd->pVertexShader)
|
||||
if (!ImGui_ImplDX11_CreateDeviceObjects())
|
||||
IM_ASSERT(0 && "ImGui_ImplDX11_CreateDeviceObjects() failed!");
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,51 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX11
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
struct ID3D11Device;
|
||||
struct ID3D11DeviceContext;
|
||||
struct ID3D11SamplerState;
|
||||
struct ID3D11Buffer;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context);
|
||||
IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data);
|
||||
|
||||
// Use if you want to reset your rendering device without losing Dear ImGui state.
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
// [BETA] Selected render state data shared with callbacks.
|
||||
// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX11_RenderDrawData() call.
|
||||
// (Please open an issue if you feel you need access to more data)
|
||||
struct ImGui_ImplDX11_RenderState
|
||||
{
|
||||
ID3D11Device* Device;
|
||||
ID3D11DeviceContext* DeviceContext;
|
||||
ID3D11SamplerState* SamplerDefault;
|
||||
ID3D11Buffer* VertexConstantBuffer;
|
||||
};
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
934
source/thirdparty/imgui/backends/imgui_impl_dx12.cpp
vendored
934
source/thirdparty/imgui/backends/imgui_impl_dx12.cpp
vendored
@@ -1,934 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX12
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
|
||||
|
||||
// The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
|
||||
// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-19: Fixed build on MinGW. (#8702, #4594)
|
||||
// 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
|
||||
// 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
|
||||
// 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429)
|
||||
// 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own.
|
||||
// 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat.
|
||||
// 2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
|
||||
// 2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple.
|
||||
// 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
|
||||
// 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
|
||||
// 2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
|
||||
// 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
|
||||
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
|
||||
// 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
|
||||
// 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
|
||||
// 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
|
||||
// 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
|
||||
// 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
|
||||
// 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2019-03-29: Misc: Various minor tidying up.
|
||||
// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
|
||||
// 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport).
|
||||
// 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_dx12.h"
|
||||
|
||||
// DirectX
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
#include <d3dcompiler.h>
|
||||
#ifdef _MSC_VER
|
||||
#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
|
||||
#endif
|
||||
|
||||
// Clang/GCC warnings with -Weverything
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
|
||||
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
|
||||
#endif
|
||||
|
||||
// MinGW workaround, see #4594
|
||||
typedef decltype(D3D12SerializeRootSignature) *_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE;
|
||||
|
||||
// DirectX12 data
|
||||
struct ImGui_ImplDX12_RenderBuffers;
|
||||
|
||||
struct ImGui_ImplDX12_Texture
|
||||
{
|
||||
ID3D12Resource* pTextureResource;
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
|
||||
|
||||
ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
struct ImGui_ImplDX12_Data
|
||||
{
|
||||
ImGui_ImplDX12_InitInfo InitInfo;
|
||||
ID3D12Device* pd3dDevice;
|
||||
ID3D12RootSignature* pRootSignature;
|
||||
ID3D12PipelineState* pPipelineState;
|
||||
ID3D12CommandQueue* pCommandQueue;
|
||||
bool commandQueueOwned;
|
||||
DXGI_FORMAT RTVFormat;
|
||||
DXGI_FORMAT DSVFormat;
|
||||
ID3D12DescriptorHeap* pd3dSrvDescHeap;
|
||||
UINT numFramesInFlight;
|
||||
|
||||
ImGui_ImplDX12_RenderBuffers* pFrameResources;
|
||||
UINT frameIndex;
|
||||
|
||||
ImGui_ImplDX12_Texture FontTexture;
|
||||
bool LegacySingleDescriptorUsed;
|
||||
|
||||
ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; }
|
||||
};
|
||||
|
||||
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
|
||||
}
|
||||
|
||||
// Buffers used during the rendering of a frame
|
||||
struct ImGui_ImplDX12_RenderBuffers
|
||||
{
|
||||
ID3D12Resource* IndexBuffer;
|
||||
ID3D12Resource* VertexBuffer;
|
||||
int IndexBufferSize;
|
||||
int VertexBufferSize;
|
||||
};
|
||||
|
||||
struct VERTEX_CONSTANT_BUFFER_DX12
|
||||
{
|
||||
float mvp[4][4];
|
||||
};
|
||||
|
||||
// Functions
|
||||
static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
|
||||
// Setup orthographic projection matrix into our constant buffer
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
|
||||
VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
|
||||
{
|
||||
float L = draw_data->DisplayPos.x;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
|
||||
float T = draw_data->DisplayPos.y;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
|
||||
float mvp[4][4] =
|
||||
{
|
||||
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 0.5f, 0.0f },
|
||||
{ (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
|
||||
};
|
||||
memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
|
||||
}
|
||||
|
||||
// Setup viewport
|
||||
D3D12_VIEWPORT vp = {};
|
||||
vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
|
||||
vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
|
||||
vp.MinDepth = 0.0f;
|
||||
vp.MaxDepth = 1.0f;
|
||||
vp.TopLeftX = vp.TopLeftY = 0.0f;
|
||||
command_list->RSSetViewports(1, &vp);
|
||||
|
||||
// Bind shader and vertex buffers
|
||||
unsigned int stride = sizeof(ImDrawVert);
|
||||
unsigned int offset = 0;
|
||||
D3D12_VERTEX_BUFFER_VIEW vbv = {};
|
||||
vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
|
||||
vbv.SizeInBytes = fr->VertexBufferSize * stride;
|
||||
vbv.StrideInBytes = stride;
|
||||
command_list->IASetVertexBuffers(0, 1, &vbv);
|
||||
D3D12_INDEX_BUFFER_VIEW ibv = {};
|
||||
ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
|
||||
ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
|
||||
ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
|
||||
command_list->IASetIndexBuffer(&ibv);
|
||||
command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
command_list->SetPipelineState(bd->pPipelineState);
|
||||
command_list->SetGraphicsRootSignature(bd->pRootSignature);
|
||||
command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
|
||||
|
||||
// Setup blend factor
|
||||
const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
|
||||
command_list->OMSetBlendFactor(blend_factor);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static inline void SafeRelease(T*& res)
|
||||
{
|
||||
if (res)
|
||||
res->Release();
|
||||
res = nullptr;
|
||||
}
|
||||
|
||||
// Render function
|
||||
void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
// Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
|
||||
// (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
|
||||
if (draw_data->Textures != nullptr)
|
||||
for (ImTextureData* tex : *draw_data->Textures)
|
||||
if (tex->Status != ImTextureStatus_OK)
|
||||
ImGui_ImplDX12_UpdateTexture(tex);
|
||||
|
||||
// FIXME: We are assuming that this only gets called once per frame!
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
bd->frameIndex = bd->frameIndex + 1;
|
||||
ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
|
||||
|
||||
// Create and grow vertex/index buffers if needed
|
||||
if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
|
||||
{
|
||||
SafeRelease(fr->VertexBuffer);
|
||||
fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
|
||||
D3D12_HEAP_PROPERTIES props = {};
|
||||
props.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
|
||||
props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
|
||||
D3D12_RESOURCE_DESC desc = {};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_UNKNOWN;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
|
||||
if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
|
||||
return;
|
||||
}
|
||||
if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
|
||||
{
|
||||
SafeRelease(fr->IndexBuffer);
|
||||
fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
|
||||
D3D12_HEAP_PROPERTIES props = {};
|
||||
props.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
|
||||
props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
|
||||
D3D12_RESOURCE_DESC desc = {};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_UNKNOWN;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
|
||||
if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
|
||||
return;
|
||||
}
|
||||
|
||||
// Upload vertex/index data into a single contiguous GPU buffer
|
||||
// During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
|
||||
void* vtx_resource, *idx_resource;
|
||||
D3D12_RANGE range = { 0, 0 };
|
||||
if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
|
||||
return;
|
||||
if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
|
||||
return;
|
||||
ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
|
||||
ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
|
||||
memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
vtx_dst += draw_list->VtxBuffer.Size;
|
||||
idx_dst += draw_list->IdxBuffer.Size;
|
||||
}
|
||||
|
||||
// During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
|
||||
range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
|
||||
IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
|
||||
fr->VertexBuffer->Unmap(0, &range);
|
||||
range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
|
||||
IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
|
||||
fr->IndexBuffer->Unmap(0, &range);
|
||||
|
||||
// Setup desired DX state
|
||||
ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
|
||||
|
||||
// Setup render state structure (for callbacks and custom texture bindings)
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
ImGui_ImplDX12_RenderState render_state;
|
||||
render_state.Device = bd->pd3dDevice;
|
||||
render_state.CommandList = command_list;
|
||||
platform_io.Renderer_RenderState = &render_state;
|
||||
|
||||
// Render command lists
|
||||
// (Because we merged all buffers into a single one, we maintain our own offset into them)
|
||||
int global_vtx_offset = 0;
|
||||
int global_idx_offset = 0;
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
ImVec2 clip_scale = draw_data->FramebufferScale;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback != nullptr)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
|
||||
else
|
||||
pcmd->UserCallback(draw_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
|
||||
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
|
||||
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle
|
||||
const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
|
||||
command_list->RSSetScissorRects(1, &r);
|
||||
|
||||
// Bind texture, Draw
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
|
||||
texture_handle.ptr = (UINT64)pcmd->GetTexID();
|
||||
command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
|
||||
command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
|
||||
}
|
||||
}
|
||||
global_idx_offset += draw_list->IdxBuffer.Size;
|
||||
global_vtx_offset += draw_list->VtxBuffer.Size;
|
||||
}
|
||||
platform_io.Renderer_RenderState = nullptr;
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX12_DestroyTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData;
|
||||
if (backend_tex == nullptr)
|
||||
return;
|
||||
IM_ASSERT(backend_tex->hFontSrvGpuDescHandle.ptr == (UINT64)tex->TexID);
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, backend_tex->hFontSrvCpuDescHandle, backend_tex->hFontSrvGpuDescHandle);
|
||||
SafeRelease(backend_tex->pTextureResource);
|
||||
backend_tex->hFontSrvCpuDescHandle.ptr = 0;
|
||||
backend_tex->hFontSrvGpuDescHandle.ptr = 0;
|
||||
IM_DELETE(backend_tex);
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex->SetTexID(ImTextureID_Invalid);
|
||||
tex->SetStatus(ImTextureStatus_Destroyed);
|
||||
tex->BackendUserData = nullptr;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
bool need_barrier_before_copy = true; // Do we need a resource barrier before we copy new data in?
|
||||
|
||||
if (tex->Status == ImTextureStatus_WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
|
||||
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
ImGui_ImplDX12_Texture* backend_tex = IM_NEW(ImGui_ImplDX12_Texture)();
|
||||
bd->InitInfo.SrvDescriptorAllocFn(&bd->InitInfo, &backend_tex->hFontSrvCpuDescHandle, &backend_tex->hFontSrvGpuDescHandle); // Allocate a desctriptor handle
|
||||
|
||||
D3D12_HEAP_PROPERTIES props = {};
|
||||
props.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
|
||||
props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
|
||||
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
desc.Alignment = 0;
|
||||
desc.Width = tex->Width;
|
||||
desc.Height = tex->Height;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.SampleDesc.Quality = 0;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
|
||||
|
||||
ID3D12Resource* pTexture = nullptr;
|
||||
bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
|
||||
|
||||
// Create SRV
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
|
||||
ZeroMemory(&srvDesc, sizeof(srvDesc));
|
||||
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
|
||||
srvDesc.Texture2D.MipLevels = desc.MipLevels;
|
||||
srvDesc.Texture2D.MostDetailedMip = 0;
|
||||
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
|
||||
bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, backend_tex->hFontSrvCpuDescHandle);
|
||||
SafeRelease(backend_tex->pTextureResource);
|
||||
backend_tex->pTextureResource = pTexture;
|
||||
|
||||
// Store identifiers
|
||||
tex->SetTexID((ImTextureID)backend_tex->hFontSrvGpuDescHandle.ptr);
|
||||
tex->BackendUserData = backend_tex;
|
||||
need_barrier_before_copy = false; // Because this is a newly-created texture it will be in D3D12_RESOURCE_STATE_COMMON and thus we don't need a barrier
|
||||
// We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below.
|
||||
}
|
||||
|
||||
if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
|
||||
{
|
||||
ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData;
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
|
||||
// We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
|
||||
// FIXME-OPT: Uploading single box even when using ImTextureStatus_WantUpdates. Could use tex->Updates[]
|
||||
// - Copy all blocks contiguously in upload buffer.
|
||||
// - Barrier before copy, submit all CopyTextureRegion(), barrier after copy.
|
||||
const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
|
||||
const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
|
||||
const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
|
||||
const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
|
||||
|
||||
// Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
|
||||
UINT upload_pitch_src = upload_w * tex->BytesPerPixel;
|
||||
UINT upload_pitch_dst = (upload_pitch_src + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
|
||||
UINT upload_size = upload_pitch_dst * upload_h;
|
||||
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
ZeroMemory(&desc, sizeof(desc));
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Alignment = 0;
|
||||
desc.Width = upload_size;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_UNKNOWN;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.SampleDesc.Quality = 0;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
|
||||
|
||||
D3D12_HEAP_PROPERTIES props;
|
||||
memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
|
||||
props.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
|
||||
props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
|
||||
|
||||
// FIXME-OPT: Can upload buffer be reused?
|
||||
ID3D12Resource* uploadBuffer = nullptr;
|
||||
HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer));
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
|
||||
// Create temporary command list and execute immediately
|
||||
ID3D12Fence* fence = nullptr;
|
||||
hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
|
||||
HANDLE event = ::CreateEvent(0, 0, 0, 0);
|
||||
IM_ASSERT(event != nullptr);
|
||||
|
||||
// FIXME-OPT: Create once and reuse?
|
||||
ID3D12CommandAllocator* cmdAlloc = nullptr;
|
||||
hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
|
||||
// FIXME-OPT: Can be use the one from user? (pass ID3D12GraphicsCommandList* to ImGui_ImplDX12_UpdateTextures)
|
||||
ID3D12GraphicsCommandList* cmdList = nullptr;
|
||||
hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList));
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
|
||||
// Copy to upload buffer
|
||||
void* mapped = nullptr;
|
||||
D3D12_RANGE range = { 0, upload_size };
|
||||
hr = uploadBuffer->Map(0, &range, &mapped);
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
for (int y = 0; y < upload_h; y++)
|
||||
memcpy((void*)((uintptr_t)mapped + y * upload_pitch_dst), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch_src);
|
||||
uploadBuffer->Unmap(0, &range);
|
||||
|
||||
if (need_barrier_before_copy)
|
||||
{
|
||||
D3D12_RESOURCE_BARRIER barrier = {};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
|
||||
barrier.Transition.pResource = backend_tex->pTextureResource;
|
||||
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
|
||||
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
cmdList->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
|
||||
D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
|
||||
{
|
||||
srcLocation.pResource = uploadBuffer;
|
||||
srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
srcLocation.PlacedFootprint.Footprint.Width = upload_w;
|
||||
srcLocation.PlacedFootprint.Footprint.Height = upload_h;
|
||||
srcLocation.PlacedFootprint.Footprint.Depth = 1;
|
||||
srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch_dst;
|
||||
dstLocation.pResource = backend_tex->pTextureResource;
|
||||
dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
dstLocation.SubresourceIndex = 0;
|
||||
}
|
||||
cmdList->CopyTextureRegion(&dstLocation, upload_x, upload_y, 0, &srcLocation, nullptr);
|
||||
|
||||
{
|
||||
D3D12_RESOURCE_BARRIER barrier = {};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
|
||||
barrier.Transition.pResource = backend_tex->pTextureResource;
|
||||
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
|
||||
cmdList->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
hr = cmdList->Close();
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
|
||||
ID3D12CommandQueue* cmdQueue = bd->pCommandQueue;
|
||||
cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
|
||||
hr = cmdQueue->Signal(fence, 1);
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
|
||||
// FIXME-OPT: Suboptimal?
|
||||
// - To remove this may need to create NumFramesInFlight x ImGui_ImplDX12_FrameContext in backend data (mimick docking version)
|
||||
// - Store per-frame in flight: upload buffer?
|
||||
// - Where do cmdList and cmdAlloc fit?
|
||||
fence->SetEventOnCompletion(1, event);
|
||||
::WaitForSingleObject(event, INFINITE);
|
||||
|
||||
cmdList->Release();
|
||||
cmdAlloc->Release();
|
||||
::CloseHandle(event);
|
||||
fence->Release();
|
||||
uploadBuffer->Release();
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
|
||||
if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames >= (int)bd->numFramesInFlight)
|
||||
ImGui_ImplDX12_DestroyTexture(tex);
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX12_CreateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
if (!bd || !bd->pd3dDevice)
|
||||
return false;
|
||||
if (bd->pPipelineState)
|
||||
ImGui_ImplDX12_InvalidateDeviceObjects();
|
||||
|
||||
// Create the root signature
|
||||
{
|
||||
D3D12_DESCRIPTOR_RANGE descRange = {};
|
||||
descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
|
||||
descRange.NumDescriptors = 1;
|
||||
descRange.BaseShaderRegister = 0;
|
||||
descRange.RegisterSpace = 0;
|
||||
descRange.OffsetInDescriptorsFromTableStart = 0;
|
||||
|
||||
D3D12_ROOT_PARAMETER param[2] = {};
|
||||
|
||||
param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
|
||||
param[0].Constants.ShaderRegister = 0;
|
||||
param[0].Constants.RegisterSpace = 0;
|
||||
param[0].Constants.Num32BitValues = 16;
|
||||
param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
|
||||
|
||||
param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
|
||||
param[1].DescriptorTable.NumDescriptorRanges = 1;
|
||||
param[1].DescriptorTable.pDescriptorRanges = &descRange;
|
||||
param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
|
||||
|
||||
// Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
|
||||
D3D12_STATIC_SAMPLER_DESC staticSampler = {};
|
||||
staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
|
||||
staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
|
||||
staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
|
||||
staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
|
||||
staticSampler.MipLODBias = 0.f;
|
||||
staticSampler.MaxAnisotropy = 0;
|
||||
staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
|
||||
staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
|
||||
staticSampler.MinLOD = 0.f;
|
||||
staticSampler.MaxLOD = D3D12_FLOAT32_MAX;
|
||||
staticSampler.ShaderRegister = 0;
|
||||
staticSampler.RegisterSpace = 0;
|
||||
staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
|
||||
|
||||
D3D12_ROOT_SIGNATURE_DESC desc = {};
|
||||
desc.NumParameters = _countof(param);
|
||||
desc.pParameters = param;
|
||||
desc.NumStaticSamplers = 1;
|
||||
desc.pStaticSamplers = &staticSampler;
|
||||
desc.Flags =
|
||||
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
|
||||
D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
|
||||
D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
|
||||
D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
|
||||
|
||||
// Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
|
||||
// See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
|
||||
static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
|
||||
if (d3d12_dll == nullptr)
|
||||
{
|
||||
// Attempt to load d3d12.dll from local directories. This will only succeed if
|
||||
// (1) the current OS is Windows 7, and
|
||||
// (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
|
||||
// See https://github.com/ocornut/imgui/pull/3696 for details.
|
||||
const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample
|
||||
for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
|
||||
if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
|
||||
break;
|
||||
|
||||
// If failed, we are on Windows >= 10.
|
||||
if (d3d12_dll == nullptr)
|
||||
d3d12_dll = ::LoadLibraryA("d3d12.dll");
|
||||
|
||||
if (d3d12_dll == nullptr)
|
||||
return false;
|
||||
}
|
||||
|
||||
_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
|
||||
if (D3D12SerializeRootSignatureFn == nullptr)
|
||||
return false;
|
||||
|
||||
ID3DBlob* blob = nullptr;
|
||||
if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
|
||||
return false;
|
||||
|
||||
bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
|
||||
blob->Release();
|
||||
}
|
||||
|
||||
// By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
|
||||
// If you would like to use this DX12 sample code but remove this dependency you can:
|
||||
// 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
|
||||
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
|
||||
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
|
||||
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
|
||||
psoDesc.NodeMask = 1;
|
||||
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
psoDesc.pRootSignature = bd->pRootSignature;
|
||||
psoDesc.SampleMask = UINT_MAX;
|
||||
psoDesc.NumRenderTargets = 1;
|
||||
psoDesc.RTVFormats[0] = bd->RTVFormat;
|
||||
psoDesc.DSVFormat = bd->DSVFormat;
|
||||
psoDesc.SampleDesc.Count = 1;
|
||||
psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
|
||||
|
||||
ID3DBlob* vertexShaderBlob;
|
||||
ID3DBlob* pixelShaderBlob;
|
||||
|
||||
// Create the vertex shader
|
||||
{
|
||||
static const char* vertexShader =
|
||||
"cbuffer vertexBuffer : register(b0) \
|
||||
{\
|
||||
float4x4 ProjectionMatrix; \
|
||||
};\
|
||||
struct VS_INPUT\
|
||||
{\
|
||||
float2 pos : POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
\
|
||||
PS_INPUT main(VS_INPUT input)\
|
||||
{\
|
||||
PS_INPUT output;\
|
||||
output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
|
||||
output.col = input.col;\
|
||||
output.uv = input.uv;\
|
||||
return output;\
|
||||
}";
|
||||
|
||||
if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
|
||||
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
|
||||
|
||||
// Create the input layout
|
||||
static D3D12_INPUT_ELEMENT_DESC local_layout[] =
|
||||
{
|
||||
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
|
||||
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
|
||||
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
|
||||
};
|
||||
psoDesc.InputLayout = { local_layout, 3 };
|
||||
}
|
||||
|
||||
// Create the pixel shader
|
||||
{
|
||||
static const char* pixelShader =
|
||||
"struct PS_INPUT\
|
||||
{\
|
||||
float4 pos : SV_POSITION;\
|
||||
float4 col : COLOR0;\
|
||||
float2 uv : TEXCOORD0;\
|
||||
};\
|
||||
SamplerState sampler0 : register(s0);\
|
||||
Texture2D texture0 : register(t0);\
|
||||
\
|
||||
float4 main(PS_INPUT input) : SV_Target\
|
||||
{\
|
||||
float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
|
||||
return out_col; \
|
||||
}";
|
||||
|
||||
if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
|
||||
{
|
||||
vertexShaderBlob->Release();
|
||||
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
|
||||
}
|
||||
psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
|
||||
}
|
||||
|
||||
// Create the blending setup
|
||||
{
|
||||
D3D12_BLEND_DESC& desc = psoDesc.BlendState;
|
||||
desc.AlphaToCoverageEnable = false;
|
||||
desc.RenderTarget[0].BlendEnable = true;
|
||||
desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
|
||||
desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
|
||||
desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
|
||||
desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
|
||||
desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
|
||||
}
|
||||
|
||||
// Create the rasterizer state
|
||||
{
|
||||
D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
|
||||
desc.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
desc.CullMode = D3D12_CULL_MODE_NONE;
|
||||
desc.FrontCounterClockwise = FALSE;
|
||||
desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
|
||||
desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
|
||||
desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
|
||||
desc.DepthClipEnable = true;
|
||||
desc.MultisampleEnable = FALSE;
|
||||
desc.AntialiasedLineEnable = FALSE;
|
||||
desc.ForcedSampleCount = 0;
|
||||
desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
|
||||
}
|
||||
|
||||
// Create depth-stencil State
|
||||
{
|
||||
D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
|
||||
desc.DepthEnable = false;
|
||||
desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
|
||||
desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
|
||||
desc.StencilEnable = false;
|
||||
desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
|
||||
desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
|
||||
desc.BackFace = desc.FrontFace;
|
||||
}
|
||||
|
||||
HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
|
||||
vertexShaderBlob->Release();
|
||||
pixelShaderBlob->Release();
|
||||
if (result_pipeline_state != S_OK)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX12_InvalidateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
if (!bd || !bd->pd3dDevice)
|
||||
return;
|
||||
|
||||
if (bd->commandQueueOwned)
|
||||
SafeRelease(bd->pCommandQueue);
|
||||
bd->commandQueueOwned = false;
|
||||
SafeRelease(bd->pRootSignature);
|
||||
SafeRelease(bd->pPipelineState);
|
||||
|
||||
// Destroy all textures
|
||||
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
|
||||
if (tex->RefCount == 1)
|
||||
ImGui_ImplDX12_DestroyTexture(tex);
|
||||
|
||||
for (UINT i = 0; i < bd->numFramesInFlight; i++)
|
||||
{
|
||||
ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
|
||||
SafeRelease(fr->IndexBuffer);
|
||||
SafeRelease(fr->VertexBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
|
||||
static void ImGui_ImplDX12_InitLegacySingleDescriptorMode(ImGui_ImplDX12_InitInfo* init_info)
|
||||
{
|
||||
// Wrap legacy behavior of passing space for a single descriptor
|
||||
IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
|
||||
init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!");
|
||||
*out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
|
||||
*out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
|
||||
bd->LegacySingleDescriptorUsed = true;
|
||||
};
|
||||
init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
|
||||
bd->LegacySingleDescriptorUsed = false;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
|
||||
bd->InitInfo = *init_info; // Deep copy
|
||||
init_info = &bd->InitInfo;
|
||||
|
||||
bd->pd3dDevice = init_info->Device;
|
||||
IM_ASSERT(init_info->CommandQueue != NULL);
|
||||
bd->pCommandQueue = init_info->CommandQueue;
|
||||
bd->RTVFormat = init_info->RTVFormat;
|
||||
bd->DSVFormat = init_info->DSVFormat;
|
||||
bd->numFramesInFlight = init_info->NumFramesInFlight;
|
||||
bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
|
||||
|
||||
io.BackendRendererUserData = (void*)bd;
|
||||
io.BackendRendererName = "imgui_impl_dx12";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
|
||||
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
|
||||
if (init_info->SrvDescriptorAllocFn == nullptr)
|
||||
ImGui_ImplDX12_InitLegacySingleDescriptorMode(init_info);
|
||||
#endif
|
||||
IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
|
||||
|
||||
// Create buffers with a default size (they will later be grown as needed)
|
||||
bd->frameIndex = UINT_MAX;
|
||||
bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[bd->numFramesInFlight];
|
||||
for (int i = 0; i < (int)bd->numFramesInFlight; i++)
|
||||
{
|
||||
ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
|
||||
fr->IndexBuffer = nullptr;
|
||||
fr->VertexBuffer = nullptr;
|
||||
fr->IndexBufferSize = 10000;
|
||||
fr->VertexBufferSize = 5000;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
|
||||
// Legacy initialization API Obsoleted in 1.91.5
|
||||
// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
|
||||
bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
|
||||
{
|
||||
ImGui_ImplDX12_InitInfo init_info;
|
||||
init_info.Device = device;
|
||||
init_info.NumFramesInFlight = num_frames_in_flight;
|
||||
init_info.RTVFormat = rtv_format;
|
||||
init_info.SrvDescriptorHeap = srv_descriptor_heap;
|
||||
init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
|
||||
init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;
|
||||
|
||||
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
|
||||
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
|
||||
queueDesc.NodeMask = 1;
|
||||
HRESULT hr = device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&init_info.CommandQueue));
|
||||
IM_ASSERT(SUCCEEDED(hr));
|
||||
|
||||
bool ret = ImGui_ImplDX12_Init(&init_info);
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
bd->commandQueueOwned = true;
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendFlags &= ~ImGuiBackendFlags_RendererHasTextures; // Using legacy ImGui_ImplDX12_Init() call with 1 SRV descriptor we cannot support multiple textures.
|
||||
|
||||
return ret;
|
||||
}
|
||||
#endif
|
||||
|
||||
void ImGui_ImplDX12_Shutdown()
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Clean up windows and device objects
|
||||
ImGui_ImplDX12_InvalidateDeviceObjects();
|
||||
delete[] bd->pFrameResources;
|
||||
|
||||
io.BackendRendererName = nullptr;
|
||||
io.BackendRendererUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
void ImGui_ImplDX12_NewFrame()
|
||||
{
|
||||
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
|
||||
|
||||
if (!bd->pPipelineState)
|
||||
if (!ImGui_ImplDX12_CreateDeviceObjects())
|
||||
IM_ASSERT(0 && "ImGui_ImplDX12_CreateDeviceObjects() failed!");
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,79 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX12
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
|
||||
|
||||
// The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
|
||||
// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include <dxgiformat.h> // DXGI_FORMAT
|
||||
#include <d3d12.h> // D3D12_CPU_DESCRIPTOR_HANDLE
|
||||
|
||||
// Initialization data, for ImGui_ImplDX12_Init()
|
||||
struct ImGui_ImplDX12_InitInfo
|
||||
{
|
||||
ID3D12Device* Device;
|
||||
ID3D12CommandQueue* CommandQueue; // Command queue used for queuing texture uploads.
|
||||
int NumFramesInFlight;
|
||||
DXGI_FORMAT RTVFormat; // RenderTarget format.
|
||||
DXGI_FORMAT DSVFormat; // DepthStencilView format.
|
||||
void* UserData;
|
||||
|
||||
// Allocating SRV descriptors for textures is up to the application, so we provide callbacks.
|
||||
// (current version of the backend will only allocate one descriptor, from 1.92 the backend will need to allocate more)
|
||||
ID3D12DescriptorHeap* SrvDescriptorHeap;
|
||||
void (*SrvDescriptorAllocFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_desc_handle);
|
||||
void (*SrvDescriptorFreeFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE gpu_desc_handle);
|
||||
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE LegacySingleSrvCpuDescriptor; // To facilitate transition from single descriptor to allocator callback, you may use those.
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE LegacySingleSrvGpuDescriptor;
|
||||
#endif
|
||||
|
||||
ImGui_ImplDX12_InitInfo() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* info);
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list);
|
||||
|
||||
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
|
||||
// Legacy initialization API Obsoleted in 1.91.5
|
||||
// - font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
|
||||
// - When we introduced the ImGui_ImplDX12_InitInfo struct we also added a 'ID3D12CommandQueue* CommandQueue' field.
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle);
|
||||
#endif
|
||||
|
||||
// Use if you want to reset your rendering device without losing Dear ImGui state.
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
// [BETA] Selected render state data shared with callbacks.
|
||||
// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX12_RenderDrawData() call.
|
||||
// (Please open an issue if you feel you need access to more data)
|
||||
struct ImGui_ImplDX12_RenderState
|
||||
{
|
||||
ID3D12Device* Device;
|
||||
ID3D12GraphicsCommandList* CommandList;
|
||||
};
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
478
source/thirdparty/imgui/backends/imgui_impl_dx9.cpp
vendored
478
source/thirdparty/imgui/backends/imgui_impl_dx9.cpp
vendored
@@ -1,478 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX9
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-11: DirectX9: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
|
||||
// 2024-10-07: DirectX9: Changed default texture sampler to Clamp instead of Repeat/Wrap.
|
||||
// 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575)
|
||||
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1.
|
||||
// 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states.
|
||||
// 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857).
|
||||
// 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file.
|
||||
// 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer.
|
||||
// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
|
||||
// 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects().
|
||||
// 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288.
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
|
||||
// 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
|
||||
// 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
|
||||
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
|
||||
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_dx9.h"
|
||||
|
||||
// DirectX
|
||||
#include <d3d9.h>
|
||||
|
||||
// Clang/GCC warnings with -Weverything
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
|
||||
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
|
||||
#endif
|
||||
|
||||
// DirectX data
|
||||
struct ImGui_ImplDX9_Data
|
||||
{
|
||||
LPDIRECT3DDEVICE9 pd3dDevice;
|
||||
LPDIRECT3DVERTEXBUFFER9 pVB;
|
||||
LPDIRECT3DINDEXBUFFER9 pIB;
|
||||
int VertexBufferSize;
|
||||
int IndexBufferSize;
|
||||
bool HasRgbaSupport;
|
||||
|
||||
ImGui_ImplDX9_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
|
||||
};
|
||||
|
||||
struct CUSTOMVERTEX
|
||||
{
|
||||
float pos[3];
|
||||
D3DCOLOR col;
|
||||
float uv[2];
|
||||
};
|
||||
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
|
||||
|
||||
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
|
||||
#define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL)
|
||||
#else
|
||||
#define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16))
|
||||
#endif
|
||||
|
||||
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
|
||||
}
|
||||
|
||||
// Functions
|
||||
static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
|
||||
// Setup viewport
|
||||
D3DVIEWPORT9 vp;
|
||||
vp.X = vp.Y = 0;
|
||||
vp.Width = (DWORD)draw_data->DisplaySize.x;
|
||||
vp.Height = (DWORD)draw_data->DisplaySize.y;
|
||||
vp.MinZ = 0.0f;
|
||||
vp.MaxZ = 1.0f;
|
||||
|
||||
LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
|
||||
device->SetViewport(&vp);
|
||||
|
||||
// Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling.
|
||||
device->SetPixelShader(nullptr);
|
||||
device->SetVertexShader(nullptr);
|
||||
device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
|
||||
device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
|
||||
device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
|
||||
device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
|
||||
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
device->SetRenderState(D3DRS_ZENABLE, FALSE);
|
||||
device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
|
||||
device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
|
||||
device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
|
||||
device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
|
||||
device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
|
||||
device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
|
||||
device->SetRenderState(D3DRS_FOGENABLE, FALSE);
|
||||
device->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
|
||||
device->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
|
||||
device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
|
||||
device->SetRenderState(D3DRS_CLIPPING, TRUE);
|
||||
device->SetRenderState(D3DRS_LIGHTING, FALSE);
|
||||
device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
|
||||
device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
|
||||
device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
|
||||
device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
|
||||
device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
|
||||
device->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
|
||||
device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
|
||||
device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
|
||||
device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
|
||||
device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
|
||||
device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
|
||||
device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
|
||||
|
||||
// Setup orthographic projection matrix
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
|
||||
// Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
|
||||
{
|
||||
float L = draw_data->DisplayPos.x + 0.5f;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
|
||||
float T = draw_data->DisplayPos.y + 0.5f;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
|
||||
D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } };
|
||||
D3DMATRIX mat_projection =
|
||||
{ { {
|
||||
2.0f/(R-L), 0.0f, 0.0f, 0.0f,
|
||||
0.0f, 2.0f/(T-B), 0.0f, 0.0f,
|
||||
0.0f, 0.0f, 0.5f, 0.0f,
|
||||
(L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f
|
||||
} } };
|
||||
device->SetTransform(D3DTS_WORLD, &mat_identity);
|
||||
device->SetTransform(D3DTS_VIEW, &mat_identity);
|
||||
device->SetTransform(D3DTS_PROJECTION, &mat_projection);
|
||||
}
|
||||
}
|
||||
|
||||
// Render function.
|
||||
void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
|
||||
|
||||
// Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
|
||||
// (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
|
||||
if (draw_data->Textures != nullptr)
|
||||
for (ImTextureData* tex : *draw_data->Textures)
|
||||
if (tex->Status != ImTextureStatus_OK)
|
||||
ImGui_ImplDX9_UpdateTexture(tex);
|
||||
|
||||
// Create and grow buffers if needed
|
||||
if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
|
||||
{
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
|
||||
bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
|
||||
if (device->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0)
|
||||
return;
|
||||
}
|
||||
if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
|
||||
{
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
|
||||
bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
|
||||
if (device->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0)
|
||||
return;
|
||||
}
|
||||
|
||||
// Backup the DX9 state
|
||||
IDirect3DStateBlock9* state_block = nullptr;
|
||||
if (device->CreateStateBlock(D3DSBT_ALL, &state_block) < 0)
|
||||
return;
|
||||
if (state_block->Capture() < 0)
|
||||
{
|
||||
state_block->Release();
|
||||
return;
|
||||
}
|
||||
|
||||
// Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
|
||||
D3DMATRIX last_world, last_view, last_projection;
|
||||
device->GetTransform(D3DTS_WORLD, &last_world);
|
||||
device->GetTransform(D3DTS_VIEW, &last_view);
|
||||
device->GetTransform(D3DTS_PROJECTION, &last_projection);
|
||||
|
||||
// Allocate buffers
|
||||
CUSTOMVERTEX* vtx_dst;
|
||||
ImDrawIdx* idx_dst;
|
||||
if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
|
||||
{
|
||||
state_block->Release();
|
||||
return;
|
||||
}
|
||||
if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
|
||||
{
|
||||
bd->pVB->Unlock();
|
||||
state_block->Release();
|
||||
return;
|
||||
}
|
||||
|
||||
// Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
|
||||
// FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and
|
||||
// 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR
|
||||
// 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data;
|
||||
for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
|
||||
{
|
||||
vtx_dst->pos[0] = vtx_src->pos.x;
|
||||
vtx_dst->pos[1] = vtx_src->pos.y;
|
||||
vtx_dst->pos[2] = 0.0f;
|
||||
vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col);
|
||||
vtx_dst->uv[0] = vtx_src->uv.x;
|
||||
vtx_dst->uv[1] = vtx_src->uv.y;
|
||||
vtx_dst++;
|
||||
vtx_src++;
|
||||
}
|
||||
memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
idx_dst += draw_list->IdxBuffer.Size;
|
||||
}
|
||||
bd->pVB->Unlock();
|
||||
bd->pIB->Unlock();
|
||||
device->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
|
||||
device->SetIndices(bd->pIB);
|
||||
device->SetFVF(D3DFVF_CUSTOMVERTEX);
|
||||
|
||||
// Setup desired DX state
|
||||
ImGui_ImplDX9_SetupRenderState(draw_data);
|
||||
|
||||
// Render command lists
|
||||
// (Because we merged all buffers into a single one, we maintain our own offset into them)
|
||||
int global_vtx_offset = 0;
|
||||
int global_idx_offset = 0;
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback != nullptr)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplDX9_SetupRenderState(draw_data);
|
||||
else
|
||||
pcmd->UserCallback(draw_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
|
||||
ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
|
||||
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle
|
||||
const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
|
||||
device->SetScissorRect(&r);
|
||||
|
||||
// Bind texture, Draw
|
||||
const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID();
|
||||
device->SetTexture(0, texture);
|
||||
device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)draw_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
|
||||
}
|
||||
}
|
||||
global_idx_offset += draw_list->IdxBuffer.Size;
|
||||
global_vtx_offset += draw_list->VtxBuffer.Size;
|
||||
}
|
||||
|
||||
// Restore the DX9 transform
|
||||
device->SetTransform(D3DTS_WORLD, &last_world);
|
||||
device->SetTransform(D3DTS_VIEW, &last_view);
|
||||
device->SetTransform(D3DTS_PROJECTION, &last_projection);
|
||||
|
||||
// Restore the DX9 state
|
||||
state_block->Apply();
|
||||
state_block->Release();
|
||||
}
|
||||
|
||||
static bool ImGui_ImplDX9_CheckFormatSupport(LPDIRECT3DDEVICE9 pDevice, D3DFORMAT format)
|
||||
{
|
||||
LPDIRECT3D9 pd3d = nullptr;
|
||||
if (pDevice->GetDirect3D(&pd3d) != D3D_OK)
|
||||
return false;
|
||||
D3DDEVICE_CREATION_PARAMETERS param = {};
|
||||
D3DDISPLAYMODE mode = {};
|
||||
if (pDevice->GetCreationParameters(¶m) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK)
|
||||
{
|
||||
pd3d->Release();
|
||||
return false;
|
||||
}
|
||||
// Font texture should support linear filter, color blend and write to render-target
|
||||
bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK;
|
||||
pd3d->Release();
|
||||
return support;
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)();
|
||||
io.BackendRendererUserData = (void*)bd;
|
||||
io.BackendRendererName = "imgui_impl_dx9";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = 4096;
|
||||
|
||||
bd->pd3dDevice = device;
|
||||
bd->pd3dDevice->AddRef();
|
||||
bd->HasRgbaSupport = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX9_Shutdown()
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
ImGui_ImplDX9_InvalidateDeviceObjects();
|
||||
if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
|
||||
io.BackendRendererName = nullptr;
|
||||
io.BackendRendererUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
// Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
|
||||
static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, const ImU32* src, int src_pitch, ImU32* dst, int dst_pitch, int w, int h)
|
||||
{
|
||||
#ifndef IMGUI_USE_BGRA_PACKED_COLOR
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
const bool convert_rgba_to_bgra = (!bd->HasRgbaSupport && tex_use_colors);
|
||||
#else
|
||||
const bool convert_rgba_to_bgra = false;
|
||||
IM_UNUSED(tex_use_colors);
|
||||
#endif
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
const ImU32* src_p = (const ImU32*)(const void*)((const unsigned char*)src + src_pitch * y);
|
||||
ImU32* dst_p = (ImU32*)(void*)((unsigned char*)dst + dst_pitch * y);
|
||||
if (convert_rgba_to_bgra)
|
||||
for (int x = w; x > 0; x--, src_p++, dst_p++) // Convert copy
|
||||
*dst_p = IMGUI_COL_TO_DX9_ARGB(*src_p);
|
||||
else
|
||||
memcpy(dst_p, src_p, w * 4); // Raw copy
|
||||
}
|
||||
}
|
||||
|
||||
void ImGui_ImplDX9_UpdateTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
|
||||
if (tex->Status == ImTextureStatus_WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
|
||||
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
LPDIRECT3DTEXTURE9 dx_tex = nullptr;
|
||||
HRESULT hr = bd->pd3dDevice->CreateTexture(tex->Width, tex->Height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &dx_tex, nullptr);
|
||||
if (hr < 0)
|
||||
{
|
||||
IM_ASSERT(hr >= 0 && "Backend failed to create texture!");
|
||||
return;
|
||||
}
|
||||
|
||||
D3DLOCKED_RECT locked_rect;
|
||||
if (dx_tex->LockRect(0, &locked_rect, nullptr, 0) == D3D_OK)
|
||||
{
|
||||
ImGui_ImplDX9_CopyTextureRegion(tex->UseColors, (ImU32*)tex->GetPixels(), tex->Width * 4, (ImU32*)locked_rect.pBits, (ImU32)locked_rect.Pitch, tex->Width, tex->Height);
|
||||
dx_tex->UnlockRect(0);
|
||||
}
|
||||
|
||||
// Store identifiers
|
||||
tex->SetTexID((ImTextureID)(intptr_t)dx_tex);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantUpdates)
|
||||
{
|
||||
// Update selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
|
||||
LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)(intptr_t)tex->TexID;
|
||||
RECT update_rect = { (LONG)tex->UpdateRect.x, (LONG)tex->UpdateRect.y, (LONG)(tex->UpdateRect.x + tex->UpdateRect.w), (LONG)(tex->UpdateRect.y + tex->UpdateRect.h) };
|
||||
D3DLOCKED_RECT locked_rect;
|
||||
if (backend_tex->LockRect(0, &locked_rect, &update_rect, 0) == D3D_OK)
|
||||
for (ImTextureRect& r : tex->Updates)
|
||||
ImGui_ImplDX9_CopyTextureRegion(tex->UseColors, (ImU32*)tex->GetPixelsAt(r.x, r.y), tex->Width * 4,
|
||||
(ImU32*)locked_rect.pBits + (r.x - update_rect.left) + (r.y - update_rect.top) * (locked_rect.Pitch / 4), (int)locked_rect.Pitch, r.w, r.h);
|
||||
backend_tex->UnlockRect(0);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantDestroy)
|
||||
{
|
||||
LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)tex->TexID;
|
||||
if (backend_tex == nullptr)
|
||||
return;
|
||||
IM_ASSERT(tex->TexID == (ImTextureID)(intptr_t)backend_tex);
|
||||
backend_tex->Release();
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex->SetTexID(ImTextureID_Invalid);
|
||||
tex->SetStatus(ImTextureStatus_Destroyed);
|
||||
}
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX9_CreateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
if (!bd || !bd->pd3dDevice)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX9_InvalidateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
if (!bd || !bd->pd3dDevice)
|
||||
return;
|
||||
|
||||
// Destroy all textures
|
||||
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
|
||||
if (tex->RefCount == 1)
|
||||
{
|
||||
tex->SetStatus(ImTextureStatus_WantDestroy);
|
||||
ImGui_ImplDX9_UpdateTexture(tex);
|
||||
}
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
|
||||
}
|
||||
|
||||
void ImGui_ImplDX9_NewFrame()
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX9_Init()?");
|
||||
IM_UNUSED(bd);
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,37 +0,0 @@
|
||||
// dear imgui: Renderer Backend for DirectX9
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
struct IDirect3DDevice9;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX9_Init(IDirect3DDevice9* device);
|
||||
IMGUI_IMPL_API void ImGui_ImplDX9_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data);
|
||||
|
||||
// Use if you want to reset your rendering device without losing Dear ImGui state.
|
||||
IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplDX9_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
1005
source/thirdparty/imgui/backends/imgui_impl_glfw.cpp
vendored
1005
source/thirdparty/imgui/backends/imgui_impl_glfw.cpp
vendored
File diff suppressed because it is too large
Load Diff
@@ -1,70 +0,0 @@
|
||||
// dear imgui: Platform Backend for GLFW
|
||||
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
|
||||
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Clipboard support.
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// [X] Multiple Dear ImGui contexts support.
|
||||
// Missing features or Issues:
|
||||
// [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround.
|
||||
// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
struct GLFWwindow;
|
||||
struct GLFWmonitor;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks);
|
||||
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks);
|
||||
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks);
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame();
|
||||
|
||||
// Emscripten related initialization phase methods (call after ImGui_ImplGlfw_InitForOpenGL)
|
||||
#ifdef __EMSCRIPTEN__
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector);
|
||||
//static inline void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector) { ImGui_ImplGlfw_InstallEmscriptenCallbacks(nullptr, canvas_selector); } } // Renamed in 1.91.0
|
||||
#endif
|
||||
|
||||
// GLFW callbacks install
|
||||
// - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any.
|
||||
// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks.
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window);
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window);
|
||||
|
||||
// GFLW callbacks options:
|
||||
// - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user)
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows);
|
||||
|
||||
// GLFW callbacks (individual callbacks to call yourself if you didn't install callbacks)
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event);
|
||||
|
||||
// GLFW helpers
|
||||
IMGUI_IMPL_API void ImGui_ImplGlfw_Sleep(int milliseconds);
|
||||
IMGUI_IMPL_API float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window);
|
||||
IMGUI_IMPL_API float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor);
|
||||
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
309
source/thirdparty/imgui/backends/imgui_impl_glut.cpp
vendored
309
source/thirdparty/imgui/backends/imgui_impl_glut.cpp
vendored
@@ -1,309 +0,0 @@
|
||||
// dear imgui: Platform Backend for GLUT/FreeGLUT
|
||||
// This needs to be used along with a Renderer (e.g. OpenGL2)
|
||||
|
||||
// !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!!
|
||||
// !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!!
|
||||
// !!! Nowadays, prefer using GLFW or SDL instead!
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// Missing features or Issues:
|
||||
// [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
|
||||
// [ ] Platform: Missing horizontal mouse wheel support.
|
||||
// [ ] Platform: Missing mouse cursor shape/visibility support.
|
||||
// [ ] Platform: Missing clipboard support (not supported by Glut).
|
||||
// [ ] Platform: Missing gamepad support.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2023-04-17: BREAKING: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame(). Needs to be called from the main application loop, like with every other backends.
|
||||
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
|
||||
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
|
||||
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
|
||||
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
|
||||
// 2019-04-03: Misc: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h.
|
||||
// 2019-03-25: Misc: Made io.DeltaTime always above zero.
|
||||
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
|
||||
// 2018-03-22: Added GLUT Platform binding.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_glut.h"
|
||||
#define GL_SILENCE_DEPRECATION
|
||||
#ifdef __APPLE__
|
||||
#include <GLUT/glut.h>
|
||||
#else
|
||||
#include <GL/freeglut.h>
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
|
||||
#endif
|
||||
|
||||
static int g_Time = 0; // Current time, in milliseconds
|
||||
|
||||
// Glut has one function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above.
|
||||
static ImGuiKey ImGui_ImplGLUT_KeyToImGuiKey(int key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case '\t': return ImGuiKey_Tab;
|
||||
case 256 + GLUT_KEY_LEFT: return ImGuiKey_LeftArrow;
|
||||
case 256 + GLUT_KEY_RIGHT: return ImGuiKey_RightArrow;
|
||||
case 256 + GLUT_KEY_UP: return ImGuiKey_UpArrow;
|
||||
case 256 + GLUT_KEY_DOWN: return ImGuiKey_DownArrow;
|
||||
case 256 + GLUT_KEY_PAGE_UP: return ImGuiKey_PageUp;
|
||||
case 256 + GLUT_KEY_PAGE_DOWN: return ImGuiKey_PageDown;
|
||||
case 256 + GLUT_KEY_HOME: return ImGuiKey_Home;
|
||||
case 256 + GLUT_KEY_END: return ImGuiKey_End;
|
||||
case 256 + GLUT_KEY_INSERT: return ImGuiKey_Insert;
|
||||
case 127: return ImGuiKey_Delete;
|
||||
case 8: return ImGuiKey_Backspace;
|
||||
case ' ': return ImGuiKey_Space;
|
||||
case 13: return ImGuiKey_Enter;
|
||||
case 27: return ImGuiKey_Escape;
|
||||
case 39: return ImGuiKey_Apostrophe;
|
||||
case 44: return ImGuiKey_Comma;
|
||||
case 45: return ImGuiKey_Minus;
|
||||
case 46: return ImGuiKey_Period;
|
||||
case 47: return ImGuiKey_Slash;
|
||||
case 59: return ImGuiKey_Semicolon;
|
||||
case 61: return ImGuiKey_Equal;
|
||||
case 91: return ImGuiKey_LeftBracket;
|
||||
case 92: return ImGuiKey_Backslash;
|
||||
case 93: return ImGuiKey_RightBracket;
|
||||
case 96: return ImGuiKey_GraveAccent;
|
||||
//case 0: return ImGuiKey_CapsLock;
|
||||
//case 0: return ImGuiKey_ScrollLock;
|
||||
case 256 + 0x006D: return ImGuiKey_NumLock;
|
||||
//case 0: return ImGuiKey_PrintScreen;
|
||||
//case 0: return ImGuiKey_Pause;
|
||||
//case '0': return ImGuiKey_Keypad0;
|
||||
//case '1': return ImGuiKey_Keypad1;
|
||||
//case '2': return ImGuiKey_Keypad2;
|
||||
//case '3': return ImGuiKey_Keypad3;
|
||||
//case '4': return ImGuiKey_Keypad4;
|
||||
//case '5': return ImGuiKey_Keypad5;
|
||||
//case '6': return ImGuiKey_Keypad6;
|
||||
//case '7': return ImGuiKey_Keypad7;
|
||||
//case '8': return ImGuiKey_Keypad8;
|
||||
//case '9': return ImGuiKey_Keypad9;
|
||||
//case 46: return ImGuiKey_KeypadDecimal;
|
||||
//case 47: return ImGuiKey_KeypadDivide;
|
||||
case 42: return ImGuiKey_KeypadMultiply;
|
||||
//case 45: return ImGuiKey_KeypadSubtract;
|
||||
case 43: return ImGuiKey_KeypadAdd;
|
||||
//case 13: return ImGuiKey_KeypadEnter;
|
||||
//case 0: return ImGuiKey_KeypadEqual;
|
||||
case 256 + 0x0072: return ImGuiKey_LeftCtrl;
|
||||
case 256 + 0x0070: return ImGuiKey_LeftShift;
|
||||
case 256 + 0x0074: return ImGuiKey_LeftAlt;
|
||||
//case 0: return ImGuiKey_LeftSuper;
|
||||
case 256 + 0x0073: return ImGuiKey_RightCtrl;
|
||||
case 256 + 0x0071: return ImGuiKey_RightShift;
|
||||
case 256 + 0x0075: return ImGuiKey_RightAlt;
|
||||
//case 0: return ImGuiKey_RightSuper;
|
||||
//case 0: return ImGuiKey_Menu;
|
||||
case '0': return ImGuiKey_0;
|
||||
case '1': return ImGuiKey_1;
|
||||
case '2': return ImGuiKey_2;
|
||||
case '3': return ImGuiKey_3;
|
||||
case '4': return ImGuiKey_4;
|
||||
case '5': return ImGuiKey_5;
|
||||
case '6': return ImGuiKey_6;
|
||||
case '7': return ImGuiKey_7;
|
||||
case '8': return ImGuiKey_8;
|
||||
case '9': return ImGuiKey_9;
|
||||
case 'A': case 'a': return ImGuiKey_A;
|
||||
case 'B': case 'b': return ImGuiKey_B;
|
||||
case 'C': case 'c': return ImGuiKey_C;
|
||||
case 'D': case 'd': return ImGuiKey_D;
|
||||
case 'E': case 'e': return ImGuiKey_E;
|
||||
case 'F': case 'f': return ImGuiKey_F;
|
||||
case 'G': case 'g': return ImGuiKey_G;
|
||||
case 'H': case 'h': return ImGuiKey_H;
|
||||
case 'I': case 'i': return ImGuiKey_I;
|
||||
case 'J': case 'j': return ImGuiKey_J;
|
||||
case 'K': case 'k': return ImGuiKey_K;
|
||||
case 'L': case 'l': return ImGuiKey_L;
|
||||
case 'M': case 'm': return ImGuiKey_M;
|
||||
case 'N': case 'n': return ImGuiKey_N;
|
||||
case 'O': case 'o': return ImGuiKey_O;
|
||||
case 'P': case 'p': return ImGuiKey_P;
|
||||
case 'Q': case 'q': return ImGuiKey_Q;
|
||||
case 'R': case 'r': return ImGuiKey_R;
|
||||
case 'S': case 's': return ImGuiKey_S;
|
||||
case 'T': case 't': return ImGuiKey_T;
|
||||
case 'U': case 'u': return ImGuiKey_U;
|
||||
case 'V': case 'v': return ImGuiKey_V;
|
||||
case 'W': case 'w': return ImGuiKey_W;
|
||||
case 'X': case 'x': return ImGuiKey_X;
|
||||
case 'Y': case 'y': return ImGuiKey_Y;
|
||||
case 'Z': case 'z': return ImGuiKey_Z;
|
||||
case 256 + GLUT_KEY_F1: return ImGuiKey_F1;
|
||||
case 256 + GLUT_KEY_F2: return ImGuiKey_F2;
|
||||
case 256 + GLUT_KEY_F3: return ImGuiKey_F3;
|
||||
case 256 + GLUT_KEY_F4: return ImGuiKey_F4;
|
||||
case 256 + GLUT_KEY_F5: return ImGuiKey_F5;
|
||||
case 256 + GLUT_KEY_F6: return ImGuiKey_F6;
|
||||
case 256 + GLUT_KEY_F7: return ImGuiKey_F7;
|
||||
case 256 + GLUT_KEY_F8: return ImGuiKey_F8;
|
||||
case 256 + GLUT_KEY_F9: return ImGuiKey_F9;
|
||||
case 256 + GLUT_KEY_F10: return ImGuiKey_F10;
|
||||
case 256 + GLUT_KEY_F11: return ImGuiKey_F11;
|
||||
case 256 + GLUT_KEY_F12: return ImGuiKey_F12;
|
||||
default: return ImGuiKey_None;
|
||||
}
|
||||
}
|
||||
|
||||
bool ImGui_ImplGLUT_Init()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
|
||||
#ifdef FREEGLUT
|
||||
io.BackendPlatformName = "imgui_impl_glut (freeglut)";
|
||||
#else
|
||||
io.BackendPlatformName = "imgui_impl_glut";
|
||||
#endif
|
||||
g_Time = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_InstallFuncs()
|
||||
{
|
||||
glutReshapeFunc(ImGui_ImplGLUT_ReshapeFunc);
|
||||
glutMotionFunc(ImGui_ImplGLUT_MotionFunc);
|
||||
glutPassiveMotionFunc(ImGui_ImplGLUT_MotionFunc);
|
||||
glutMouseFunc(ImGui_ImplGLUT_MouseFunc);
|
||||
#ifdef __FREEGLUT_EXT_H__
|
||||
glutMouseWheelFunc(ImGui_ImplGLUT_MouseWheelFunc);
|
||||
#endif
|
||||
glutKeyboardFunc(ImGui_ImplGLUT_KeyboardFunc);
|
||||
glutKeyboardUpFunc(ImGui_ImplGLUT_KeyboardUpFunc);
|
||||
glutSpecialFunc(ImGui_ImplGLUT_SpecialFunc);
|
||||
glutSpecialUpFunc(ImGui_ImplGLUT_SpecialUpFunc);
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_Shutdown()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendPlatformName = nullptr;
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_NewFrame()
|
||||
{
|
||||
// Setup time step
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
int current_time = glutGet(GLUT_ELAPSED_TIME);
|
||||
int delta_time_ms = (current_time - g_Time);
|
||||
if (delta_time_ms <= 0)
|
||||
delta_time_ms = 1;
|
||||
io.DeltaTime = delta_time_ms / 1000.0f;
|
||||
g_Time = current_time;
|
||||
}
|
||||
|
||||
static void ImGui_ImplGLUT_UpdateKeyModifiers()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
int glut_key_mods = glutGetModifiers();
|
||||
io.AddKeyEvent(ImGuiMod_Ctrl, (glut_key_mods & GLUT_ACTIVE_CTRL) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Shift, (glut_key_mods & GLUT_ACTIVE_SHIFT) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Alt, (glut_key_mods & GLUT_ACTIVE_ALT) != 0);
|
||||
}
|
||||
|
||||
static void ImGui_ImplGLUT_AddKeyEvent(ImGuiKey key, bool down, int native_keycode)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddKeyEvent(key, down);
|
||||
io.SetKeyEventNativeData(key, native_keycode, -1); // To support legacy indexing (<1.87 user code)
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y)
|
||||
{
|
||||
// Send character to imgui
|
||||
//printf("char_down_func %d '%c'\n", c, c);
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
if (c >= 32)
|
||||
io.AddInputCharacter((unsigned int)c);
|
||||
|
||||
ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c);
|
||||
ImGui_ImplGLUT_AddKeyEvent(key, true, c);
|
||||
ImGui_ImplGLUT_UpdateKeyModifiers();
|
||||
(void)x; (void)y; // Unused
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y)
|
||||
{
|
||||
//printf("char_up_func %d '%c'\n", c, c);
|
||||
ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c);
|
||||
ImGui_ImplGLUT_AddKeyEvent(key, false, c);
|
||||
ImGui_ImplGLUT_UpdateKeyModifiers();
|
||||
(void)x; (void)y; // Unused
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y)
|
||||
{
|
||||
//printf("key_down_func %d\n", key);
|
||||
ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256);
|
||||
ImGui_ImplGLUT_AddKeyEvent(imgui_key, true, key + 256);
|
||||
ImGui_ImplGLUT_UpdateKeyModifiers();
|
||||
(void)x; (void)y; // Unused
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y)
|
||||
{
|
||||
//printf("key_up_func %d\n", key);
|
||||
ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256);
|
||||
ImGui_ImplGLUT_AddKeyEvent(imgui_key, false, key + 256);
|
||||
ImGui_ImplGLUT_UpdateKeyModifiers();
|
||||
(void)x; (void)y; // Unused
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_MouseFunc(int glut_button, int state, int x, int y)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddMousePosEvent((float)x, (float)y);
|
||||
int button = -1;
|
||||
if (glut_button == GLUT_LEFT_BUTTON) button = 0;
|
||||
if (glut_button == GLUT_RIGHT_BUTTON) button = 1;
|
||||
if (glut_button == GLUT_MIDDLE_BUTTON) button = 2;
|
||||
if (button != -1 && (state == GLUT_DOWN || state == GLUT_UP))
|
||||
io.AddMouseButtonEvent(button, state == GLUT_DOWN);
|
||||
}
|
||||
|
||||
#ifdef __FREEGLUT_EXT_H__
|
||||
void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddMousePosEvent((float)x, (float)y);
|
||||
if (dir != 0)
|
||||
io.AddMouseWheelEvent(0.0f, dir > 0 ? 1.0f : -1.0f);
|
||||
(void)button; // Unused
|
||||
}
|
||||
#endif
|
||||
|
||||
void ImGui_ImplGLUT_ReshapeFunc(int w, int h)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.DisplaySize = ImVec2((float)w, (float)h);
|
||||
}
|
||||
|
||||
void ImGui_ImplGLUT_MotionFunc(int x, int y)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddMousePosEvent((float)x, (float)y);
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,47 +0,0 @@
|
||||
// dear imgui: Platform Backend for GLUT/FreeGLUT
|
||||
// This needs to be used along with a Renderer (e.g. OpenGL2)
|
||||
|
||||
// !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!!
|
||||
// !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!!
|
||||
// !!! Nowadays, prefer using GLFW or SDL instead!
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// Missing features or Issues:
|
||||
// [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
|
||||
// [ ] Platform: Missing horizontal mouse wheel support.
|
||||
// [ ] Platform: Missing mouse cursor shape/visibility support.
|
||||
// [ ] Platform: Missing clipboard support (not supported by Glut).
|
||||
// [ ] Platform: Missing gamepad support.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplGLUT_Init();
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_InstallFuncs();
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame();
|
||||
|
||||
// You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically,
|
||||
// or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency..
|
||||
//------------------------------------ GLUT name ---------------------------------------------- Decent Name ---------
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y); // ~ MouseWheelFunc
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y); // ~ CharPressedFunc
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc
|
||||
IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,78 +0,0 @@
|
||||
// dear imgui: Renderer Backend for Metal
|
||||
// This needs to be used along with a Platform Backend (e.g. OSX)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// ObjC API
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef __OBJC__
|
||||
|
||||
@class MTLRenderPassDescriptor;
|
||||
@protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id<MTLDevice> device);
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor);
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData,
|
||||
id<MTLCommandBuffer> commandBuffer,
|
||||
id<MTLRenderCommandEncoder> commandEncoder);
|
||||
|
||||
// Called by Init/NewFrame/Shutdown
|
||||
IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device);
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
#endif
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// C++ API
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
// Enable Metal C++ binding support with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file
|
||||
// More info about using Metal from C++: https://developer.apple.com/metal/cpp/
|
||||
|
||||
#ifdef IMGUI_IMPL_METAL_CPP
|
||||
#include <Metal/Metal.hpp>
|
||||
#ifndef __OBJC__
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplMetal_Init(MTL::Device* device);
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor);
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
|
||||
MTL::CommandBuffer* commandBuffer,
|
||||
MTL::RenderCommandEncoder* commandEncoder);
|
||||
|
||||
// Called by Init/NewFrame/Shutdown
|
||||
IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device);
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
652
source/thirdparty/imgui/backends/imgui_impl_metal.mm
vendored
652
source/thirdparty/imgui/backends/imgui_impl_metal.mm
vendored
@@ -1,652 +0,0 @@
|
||||
// dear imgui: Renderer Backend for Metal
|
||||
// This needs to be used along with a Platform Backend (e.g. OSX)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplMetal_CreateFontsTexture() and ImGui_ImplMetal_DestroyFontsTexture().
|
||||
// 2025-02-03: Metal: Crash fix. (#8367)
|
||||
// 2024-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419).
|
||||
// 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'.
|
||||
// 2022-07-05: Metal: Add dispatch synchronization.
|
||||
// 2022-06-30: Metal: Use __bridge for ARC based systems.
|
||||
// 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler.
|
||||
// 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
|
||||
// 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code).
|
||||
// 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file.
|
||||
// 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464)
|
||||
// 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer.
|
||||
// 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst.
|
||||
// 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
|
||||
// 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-07-05: Metal: Added new Metal backend implementation.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_metal.h"
|
||||
#import <time.h>
|
||||
#import <Metal/Metal.h>
|
||||
|
||||
#pragma mark - Support classes
|
||||
|
||||
// A wrapper around a MTLBuffer object that knows the last time it was reused
|
||||
@interface MetalBuffer : NSObject
|
||||
@property (nonatomic, strong) id<MTLBuffer> buffer;
|
||||
@property (nonatomic, assign) double lastReuseTime;
|
||||
- (instancetype)initWithBuffer:(id<MTLBuffer>)buffer;
|
||||
@end
|
||||
|
||||
// An object that encapsulates the data necessary to uniquely identify a
|
||||
// render pipeline state. These are used as cache keys.
|
||||
@interface FramebufferDescriptor : NSObject<NSCopying>
|
||||
@property (nonatomic, assign) unsigned long sampleCount;
|
||||
@property (nonatomic, assign) MTLPixelFormat colorPixelFormat;
|
||||
@property (nonatomic, assign) MTLPixelFormat depthPixelFormat;
|
||||
@property (nonatomic, assign) MTLPixelFormat stencilPixelFormat;
|
||||
- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor;
|
||||
@end
|
||||
|
||||
@interface MetalTexture : NSObject
|
||||
@property (nonatomic, strong) id<MTLTexture> metalTexture;
|
||||
- (instancetype)initWithTexture:(id<MTLTexture>)metalTexture;
|
||||
@end
|
||||
|
||||
// A singleton that stores long-lived objects that are needed by the Metal
|
||||
// renderer backend. Stores the render pipeline state cache and the default
|
||||
// font texture, and manages the reusable buffer cache.
|
||||
@interface MetalContext : NSObject
|
||||
@property (nonatomic, strong) id<MTLDevice> device;
|
||||
@property (nonatomic, strong) id<MTLDepthStencilState> depthStencilState;
|
||||
@property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; // framebuffer descriptor for current frame; transient
|
||||
@property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors
|
||||
@property (nonatomic, strong) NSMutableArray<MetalBuffer*>* bufferCache;
|
||||
@property (nonatomic, assign) double lastBufferCachePurge;
|
||||
- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device;
|
||||
- (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device;
|
||||
@end
|
||||
|
||||
struct ImGui_ImplMetal_Data
|
||||
{
|
||||
MetalContext* SharedMetalContext;
|
||||
|
||||
ImGui_ImplMetal_Data() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
|
||||
static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); }
|
||||
|
||||
static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
|
||||
|
||||
#ifdef IMGUI_IMPL_METAL_CPP
|
||||
|
||||
#pragma mark - Dear ImGui Metal C++ Backend API
|
||||
|
||||
bool ImGui_ImplMetal_Init(MTL::Device* device)
|
||||
{
|
||||
return ImGui_ImplMetal_Init((__bridge id<MTLDevice>)(device));
|
||||
}
|
||||
|
||||
void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor)
|
||||
{
|
||||
ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor));
|
||||
}
|
||||
|
||||
void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
|
||||
MTL::CommandBuffer* commandBuffer,
|
||||
MTL::RenderCommandEncoder* commandEncoder)
|
||||
{
|
||||
ImGui_ImplMetal_RenderDrawData(draw_data,
|
||||
(__bridge id<MTLCommandBuffer>)(commandBuffer),
|
||||
(__bridge id<MTLRenderCommandEncoder>)(commandEncoder));
|
||||
|
||||
}
|
||||
|
||||
bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device)
|
||||
{
|
||||
return ImGui_ImplMetal_CreateDeviceObjects((__bridge id<MTLDevice>)(device));
|
||||
}
|
||||
|
||||
#endif // #ifdef IMGUI_IMPL_METAL_CPP
|
||||
|
||||
#pragma mark - Dear ImGui Metal Backend API
|
||||
|
||||
bool ImGui_ImplMetal_Init(id<MTLDevice> device)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
|
||||
|
||||
ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)();
|
||||
io.BackendRendererUserData = (void*)bd;
|
||||
io.BackendRendererName = "imgui_impl_metal";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
|
||||
bd->SharedMetalContext = [[MetalContext alloc] init];
|
||||
bd->SharedMetalContext.device = device;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplMetal_Shutdown()
|
||||
{
|
||||
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
|
||||
IM_UNUSED(bd);
|
||||
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
|
||||
ImGui_ImplMetal_DestroyDeviceObjects();
|
||||
ImGui_ImplMetal_DestroyBackendData();
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendRendererName = nullptr;
|
||||
io.BackendRendererUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
|
||||
}
|
||||
|
||||
void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor)
|
||||
{
|
||||
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
|
||||
IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?");
|
||||
#ifdef IMGUI_IMPL_METAL_CPP
|
||||
bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease];
|
||||
#else
|
||||
bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
|
||||
#endif
|
||||
if (bd->SharedMetalContext.depthStencilState == nil)
|
||||
ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device);
|
||||
}
|
||||
|
||||
static void ImGui_ImplMetal_SetupRenderState(ImDrawData* draw_data, id<MTLCommandBuffer> commandBuffer,
|
||||
id<MTLRenderCommandEncoder> commandEncoder, id<MTLRenderPipelineState> renderPipelineState,
|
||||
MetalBuffer* vertexBuffer, size_t vertexBufferOffset)
|
||||
{
|
||||
IM_UNUSED(commandBuffer);
|
||||
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
|
||||
[commandEncoder setCullMode:MTLCullModeNone];
|
||||
[commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState];
|
||||
|
||||
// Setup viewport, orthographic projection matrix
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to
|
||||
// draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
|
||||
MTLViewport viewport =
|
||||
{
|
||||
.originX = 0.0,
|
||||
.originY = 0.0,
|
||||
.width = (double)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x),
|
||||
.height = (double)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y),
|
||||
.znear = 0.0,
|
||||
.zfar = 1.0
|
||||
};
|
||||
[commandEncoder setViewport:viewport];
|
||||
|
||||
float L = draw_data->DisplayPos.x;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
|
||||
float T = draw_data->DisplayPos.y;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
|
||||
float N = (float)viewport.znear;
|
||||
float F = (float)viewport.zfar;
|
||||
const float ortho_projection[4][4] =
|
||||
{
|
||||
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 1/(F-N), 0.0f },
|
||||
{ (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f },
|
||||
};
|
||||
[commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1];
|
||||
|
||||
[commandEncoder setRenderPipelineState:renderPipelineState];
|
||||
|
||||
[commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0];
|
||||
[commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0];
|
||||
}
|
||||
|
||||
// Metal Render function.
|
||||
void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder)
|
||||
{
|
||||
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
|
||||
MetalContext* ctx = bd->SharedMetalContext;
|
||||
|
||||
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
|
||||
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
|
||||
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
|
||||
if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0)
|
||||
return;
|
||||
|
||||
// Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
|
||||
// (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
|
||||
if (draw_data->Textures != nullptr)
|
||||
for (ImTextureData* tex : *draw_data->Textures)
|
||||
if (tex->Status != ImTextureStatus_OK)
|
||||
ImGui_ImplMetal_UpdateTexture(tex);
|
||||
|
||||
// Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame
|
||||
// The hit rate for this cache should be very near 100%.
|
||||
id<MTLRenderPipelineState> renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor];
|
||||
if (renderPipelineState == nil)
|
||||
{
|
||||
// No luck; make a new render pipeline state
|
||||
renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device];
|
||||
|
||||
// Cache render pipeline state for later reuse
|
||||
ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState;
|
||||
}
|
||||
|
||||
size_t vertexBufferLength = (size_t)draw_data->TotalVtxCount * sizeof(ImDrawVert);
|
||||
size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx);
|
||||
MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device];
|
||||
MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device];
|
||||
|
||||
ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0);
|
||||
|
||||
// Will project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
|
||||
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
|
||||
|
||||
// Render command lists
|
||||
size_t vertexBufferOffset = 0;
|
||||
size_t indexBufferOffset = 0;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
|
||||
memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
|
||||
memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
|
||||
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset);
|
||||
else
|
||||
pcmd->UserCallback(draw_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
|
||||
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
|
||||
|
||||
// Clamp to viewport as setScissorRect() won't accept values that are off bounds
|
||||
if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
|
||||
if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
|
||||
if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
|
||||
if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
|
||||
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
|
||||
continue;
|
||||
if (pcmd->ElemCount == 0) // drawIndexedPrimitives() validation doesn't accept this
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle
|
||||
MTLScissorRect scissorRect =
|
||||
{
|
||||
.x = NSUInteger(clip_min.x),
|
||||
.y = NSUInteger(clip_min.y),
|
||||
.width = NSUInteger(clip_max.x - clip_min.x),
|
||||
.height = NSUInteger(clip_max.y - clip_min.y)
|
||||
};
|
||||
[commandEncoder setScissorRect:scissorRect];
|
||||
|
||||
// Bind texture, Draw
|
||||
if (ImTextureID tex_id = pcmd->GetTexID())
|
||||
[commandEncoder setFragmentTexture:(__bridge id<MTLTexture>)(void*)(intptr_t)(tex_id) atIndex:0];
|
||||
|
||||
[commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0];
|
||||
[commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
|
||||
indexCount:pcmd->ElemCount
|
||||
indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
|
||||
indexBuffer:indexBuffer.buffer
|
||||
indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)];
|
||||
}
|
||||
}
|
||||
|
||||
vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert);
|
||||
indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx);
|
||||
}
|
||||
|
||||
MetalContext* sharedMetalContext = bd->SharedMetalContext;
|
||||
[commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>)
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
@synchronized(sharedMetalContext.bufferCache)
|
||||
{
|
||||
[sharedMetalContext.bufferCache addObject:vertexBuffer];
|
||||
[sharedMetalContext.bufferCache addObject:indexBuffer];
|
||||
}
|
||||
});
|
||||
}];
|
||||
}
|
||||
|
||||
static void ImGui_ImplMetal_DestroyTexture(ImTextureData* tex)
|
||||
{
|
||||
MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData);
|
||||
if (backend_tex == nullptr)
|
||||
return;
|
||||
IM_ASSERT(backend_tex.metalTexture == (__bridge id<MTLTexture>)(void*)(intptr_t)tex->TexID);
|
||||
backend_tex.metalTexture = nil;
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex->SetTexID(ImTextureID_Invalid);
|
||||
tex->SetStatus(ImTextureStatus_Destroyed);
|
||||
tex->BackendUserData = nullptr;
|
||||
}
|
||||
|
||||
void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex)
|
||||
{
|
||||
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
|
||||
if (tex->Status == ImTextureStatus_WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
|
||||
IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
|
||||
// We are retrieving and uploading the font atlas as a 4-channels RGBA texture here.
|
||||
// In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth.
|
||||
// However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures.
|
||||
// You can make that change in your implementation.
|
||||
MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
|
||||
width:(NSUInteger)tex->Width
|
||||
height:(NSUInteger)tex->Height
|
||||
mipmapped:NO];
|
||||
textureDescriptor.usage = MTLTextureUsageShaderRead;
|
||||
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
|
||||
textureDescriptor.storageMode = MTLStorageModeManaged;
|
||||
#else
|
||||
textureDescriptor.storageMode = MTLStorageModeShared;
|
||||
#endif
|
||||
id <MTLTexture> texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor];
|
||||
[texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4];
|
||||
MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture];
|
||||
|
||||
// Store identifiers
|
||||
tex->SetTexID((ImTextureID)(intptr_t)texture);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
tex->BackendUserData = (__bridge_retained void*)(backend_tex);
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantUpdates)
|
||||
{
|
||||
// Update selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
|
||||
MetalTexture* backend_tex = (__bridge MetalTexture*)(tex->BackendUserData);
|
||||
for (ImTextureRect& r : tex->Updates)
|
||||
{
|
||||
[backend_tex.metalTexture replaceRegion:MTLRegionMake2D((NSUInteger)r.x, (NSUInteger)r.y, (NSUInteger)r.w, (NSUInteger)r.h)
|
||||
mipmapLevel:0
|
||||
withBytes:tex->GetPixelsAt(r.x, r.y)
|
||||
bytesPerRow:(NSUInteger)tex->Width * 4];
|
||||
}
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
|
||||
{
|
||||
ImGui_ImplMetal_DestroyTexture(tex);
|
||||
}
|
||||
}
|
||||
|
||||
bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device)
|
||||
{
|
||||
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
|
||||
MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init];
|
||||
depthStencilDescriptor.depthWriteEnabled = NO;
|
||||
depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
|
||||
bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor];
|
||||
#ifdef IMGUI_IMPL_METAL_CPP
|
||||
[depthStencilDescriptor release];
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplMetal_DestroyDeviceObjects()
|
||||
{
|
||||
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
|
||||
|
||||
// Destroy all textures
|
||||
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
|
||||
if (tex->RefCount == 1)
|
||||
ImGui_ImplMetal_DestroyTexture(tex);
|
||||
|
||||
[bd->SharedMetalContext.renderPipelineStateCache removeAllObjects];
|
||||
}
|
||||
|
||||
#pragma mark - MetalBuffer implementation
|
||||
|
||||
@implementation MetalBuffer
|
||||
- (instancetype)initWithBuffer:(id<MTLBuffer>)buffer
|
||||
{
|
||||
if ((self = [super init]))
|
||||
{
|
||||
_buffer = buffer;
|
||||
_lastReuseTime = GetMachAbsoluteTimeInSeconds();
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@end
|
||||
|
||||
#pragma mark - FramebufferDescriptor implementation
|
||||
|
||||
@implementation FramebufferDescriptor
|
||||
- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor
|
||||
{
|
||||
if ((self = [super init]))
|
||||
{
|
||||
_sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount;
|
||||
_colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat;
|
||||
_depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat;
|
||||
_stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (nonnull id)copyWithZone:(nullable NSZone*)zone
|
||||
{
|
||||
FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init];
|
||||
copy.sampleCount = self.sampleCount;
|
||||
copy.colorPixelFormat = self.colorPixelFormat;
|
||||
copy.depthPixelFormat = self.depthPixelFormat;
|
||||
copy.stencilPixelFormat = self.stencilPixelFormat;
|
||||
return copy;
|
||||
}
|
||||
|
||||
- (NSUInteger)hash
|
||||
{
|
||||
NSUInteger sc = _sampleCount & 0x3;
|
||||
NSUInteger cf = _colorPixelFormat & 0x3FF;
|
||||
NSUInteger df = _depthPixelFormat & 0x3FF;
|
||||
NSUInteger sf = _stencilPixelFormat & 0x3FF;
|
||||
NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc;
|
||||
return hash;
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)object
|
||||
{
|
||||
FramebufferDescriptor* other = object;
|
||||
if (![other isKindOfClass:[FramebufferDescriptor class]])
|
||||
return NO;
|
||||
return other.sampleCount == self.sampleCount &&
|
||||
other.colorPixelFormat == self.colorPixelFormat &&
|
||||
other.depthPixelFormat == self.depthPixelFormat &&
|
||||
other.stencilPixelFormat == self.stencilPixelFormat;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark - MetalTexture implementation
|
||||
|
||||
@implementation MetalTexture
|
||||
- (instancetype)initWithTexture:(id<MTLTexture>)metalTexture
|
||||
{
|
||||
if ((self = [super init]))
|
||||
self.metalTexture = metalTexture;
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark - MetalContext implementation
|
||||
|
||||
@implementation MetalContext
|
||||
- (instancetype)init
|
||||
{
|
||||
if ((self = [super init]))
|
||||
{
|
||||
self.renderPipelineStateCache = [NSMutableDictionary dictionary];
|
||||
self.bufferCache = [NSMutableArray array];
|
||||
_lastBufferCachePurge = GetMachAbsoluteTimeInSeconds();
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device
|
||||
{
|
||||
uint64_t now = GetMachAbsoluteTimeInSeconds();
|
||||
|
||||
@synchronized(self.bufferCache)
|
||||
{
|
||||
// Purge old buffers that haven't been useful for a while
|
||||
if (now - self.lastBufferCachePurge > 1.0)
|
||||
{
|
||||
NSMutableArray* survivors = [NSMutableArray array];
|
||||
for (MetalBuffer* candidate in self.bufferCache)
|
||||
if (candidate.lastReuseTime > self.lastBufferCachePurge)
|
||||
[survivors addObject:candidate];
|
||||
self.bufferCache = [survivors mutableCopy];
|
||||
self.lastBufferCachePurge = now;
|
||||
}
|
||||
|
||||
// See if we have a buffer we can reuse
|
||||
MetalBuffer* bestCandidate = nil;
|
||||
for (MetalBuffer* candidate in self.bufferCache)
|
||||
if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime))
|
||||
bestCandidate = candidate;
|
||||
|
||||
if (bestCandidate != nil)
|
||||
{
|
||||
[self.bufferCache removeObject:bestCandidate];
|
||||
bestCandidate.lastReuseTime = now;
|
||||
return bestCandidate;
|
||||
}
|
||||
}
|
||||
|
||||
// No luck; make a new buffer
|
||||
id<MTLBuffer> backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared];
|
||||
return [[MetalBuffer alloc] initWithBuffer:backing];
|
||||
}
|
||||
|
||||
// Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
|
||||
- (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device
|
||||
{
|
||||
NSError* error = nil;
|
||||
|
||||
NSString* shaderSource = @""
|
||||
"#include <metal_stdlib>\n"
|
||||
"using namespace metal;\n"
|
||||
"\n"
|
||||
"struct Uniforms {\n"
|
||||
" float4x4 projectionMatrix;\n"
|
||||
"};\n"
|
||||
"\n"
|
||||
"struct VertexIn {\n"
|
||||
" float2 position [[attribute(0)]];\n"
|
||||
" float2 texCoords [[attribute(1)]];\n"
|
||||
" uchar4 color [[attribute(2)]];\n"
|
||||
"};\n"
|
||||
"\n"
|
||||
"struct VertexOut {\n"
|
||||
" float4 position [[position]];\n"
|
||||
" float2 texCoords;\n"
|
||||
" float4 color;\n"
|
||||
"};\n"
|
||||
"\n"
|
||||
"vertex VertexOut vertex_main(VertexIn in [[stage_in]],\n"
|
||||
" constant Uniforms &uniforms [[buffer(1)]]) {\n"
|
||||
" VertexOut out;\n"
|
||||
" out.position = uniforms.projectionMatrix * float4(in.position, 0, 1);\n"
|
||||
" out.texCoords = in.texCoords;\n"
|
||||
" out.color = float4(in.color) / float4(255.0);\n"
|
||||
" return out;\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
"fragment half4 fragment_main(VertexOut in [[stage_in]],\n"
|
||||
" texture2d<half, access::sample> texture [[texture(0)]]) {\n"
|
||||
" constexpr sampler linearSampler(coord::normalized, min_filter::linear, mag_filter::linear, mip_filter::linear);\n"
|
||||
" half4 texColor = texture.sample(linearSampler, in.texCoords);\n"
|
||||
" return half4(in.color) * texColor;\n"
|
||||
"}\n";
|
||||
|
||||
id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
|
||||
if (library == nil)
|
||||
{
|
||||
NSLog(@"Error: failed to create Metal library: %@", error);
|
||||
return nil;
|
||||
}
|
||||
|
||||
id<MTLFunction> vertexFunction = [library newFunctionWithName:@"vertex_main"];
|
||||
id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"fragment_main"];
|
||||
|
||||
if (vertexFunction == nil || fragmentFunction == nil)
|
||||
{
|
||||
NSLog(@"Error: failed to find Metal shader functions in library: %@", error);
|
||||
return nil;
|
||||
}
|
||||
|
||||
MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
|
||||
vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos);
|
||||
vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
|
||||
vertexDescriptor.attributes[0].bufferIndex = 0;
|
||||
vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv);
|
||||
vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
|
||||
vertexDescriptor.attributes[1].bufferIndex = 0;
|
||||
vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col);
|
||||
vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
|
||||
vertexDescriptor.attributes[2].bufferIndex = 0;
|
||||
vertexDescriptor.layouts[0].stepRate = 1;
|
||||
vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
|
||||
vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert);
|
||||
|
||||
MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
|
||||
pipelineDescriptor.vertexFunction = vertexFunction;
|
||||
pipelineDescriptor.fragmentFunction = fragmentFunction;
|
||||
pipelineDescriptor.vertexDescriptor = vertexDescriptor;
|
||||
pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount;
|
||||
pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat;
|
||||
pipelineDescriptor.colorAttachments[0].blendingEnabled = YES;
|
||||
pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
|
||||
pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
|
||||
pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
|
||||
pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
|
||||
pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
|
||||
pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
|
||||
pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat;
|
||||
pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat;
|
||||
|
||||
id<MTLRenderPipelineState> renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
|
||||
if (error != nil)
|
||||
NSLog(@"Error: failed to create Metal pipeline state: %@", error);
|
||||
|
||||
return renderPipelineState;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,346 +0,0 @@
|
||||
// dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline)
|
||||
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// Missing features or Issues:
|
||||
// [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
|
||||
// **Prefer using the code in imgui_impl_opengl3.cpp**
|
||||
// This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
|
||||
// If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
|
||||
// complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
|
||||
// confuse your GPU driver.
|
||||
// The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL2_CreateFontsTexture() and ImGui_ImplOpenGL2_DestroyFontsTexture().
|
||||
// 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap.
|
||||
// 2024-06-28: OpenGL: ImGui_ImplOpenGL2_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL2_DestroyFontsTexture(). (#7748)
|
||||
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
|
||||
// 2021-12-08: OpenGL: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-01-03: OpenGL: Backup, setup and restore GL_SHADE_MODEL state, disable GL_STENCIL_TEST and disable GL_NORMAL_ARRAY client state to increase compatibility with legacy OpenGL applications.
|
||||
// 2020-01-23: OpenGL: Backup, setup and restore GL_TEXTURE_ENV to increase compatibility with legacy OpenGL applications.
|
||||
// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications.
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_opengl2.cpp/.h away from the old combined GLFW/SDL+OpenGL2 examples.
|
||||
// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
|
||||
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplOpenGL2_RenderDrawData() in the .h file so you can call it yourself.
|
||||
// 2017-09-01: OpenGL: Save and restore current polygon mode.
|
||||
// 2016-09-10: OpenGL: Uploading font texture as RGBA32 to increase compatibility with users shaders (not ideal).
|
||||
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_opengl2.h"
|
||||
#include <stdint.h> // intptr_t
|
||||
|
||||
// Clang/GCC warnings with -Weverything
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used
|
||||
#pragma clang diagnostic ignored "-Wnonportable-system-include-path"
|
||||
#endif
|
||||
|
||||
// Include OpenGL header (without an OpenGL loader) requires a bit of fiddling
|
||||
#if defined(_WIN32) && !defined(APIENTRY)
|
||||
#define APIENTRY __stdcall // It is customary to use APIENTRY for OpenGL function pointer declarations on all platforms. Additionally, the Windows OpenGL header needs APIENTRY.
|
||||
#endif
|
||||
#if defined(_WIN32) && !defined(WINGDIAPI)
|
||||
#define WINGDIAPI __declspec(dllimport) // Some Windows OpenGL headers need this
|
||||
#endif
|
||||
#if defined(__APPLE__)
|
||||
#define GL_SILENCE_DEPRECATION
|
||||
#include <OpenGL/gl.h>
|
||||
#else
|
||||
#include <GL/gl.h>
|
||||
#endif
|
||||
|
||||
// [Debugging]
|
||||
//#define IMGUI_IMPL_OPENGL_DEBUG
|
||||
#ifdef IMGUI_IMPL_OPENGL_DEBUG
|
||||
#include <stdio.h>
|
||||
#define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check
|
||||
#else
|
||||
#define GL_CALL(_CALL) _CALL // Call without error check
|
||||
#endif
|
||||
|
||||
// OpenGL data
|
||||
struct ImGui_ImplOpenGL2_Data
|
||||
{
|
||||
ImGui_ImplOpenGL2_Data() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
static ImGui_ImplOpenGL2_Data* ImGui_ImplOpenGL2_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
|
||||
}
|
||||
|
||||
// Functions
|
||||
bool ImGui_ImplOpenGL2_Init()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplOpenGL2_Data* bd = IM_NEW(ImGui_ImplOpenGL2_Data)();
|
||||
io.BackendRendererUserData = (void*)bd;
|
||||
io.BackendRendererName = "imgui_impl_opengl2";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplOpenGL2_Shutdown()
|
||||
{
|
||||
ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
ImGui_ImplOpenGL2_DestroyDeviceObjects();
|
||||
io.BackendRendererName = nullptr;
|
||||
io.BackendRendererUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasTextures);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
void ImGui_ImplOpenGL2_NewFrame()
|
||||
{
|
||||
ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL2_Init()?");
|
||||
IM_UNUSED(bd);
|
||||
}
|
||||
|
||||
static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height)
|
||||
{
|
||||
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||
//glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // In order to composite our output buffer we need to preserve alpha
|
||||
glDisable(GL_CULL_FACE);
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glDisable(GL_STENCIL_TEST);
|
||||
glDisable(GL_LIGHTING);
|
||||
glDisable(GL_COLOR_MATERIAL);
|
||||
glEnable(GL_SCISSOR_TEST);
|
||||
glEnableClientState(GL_VERTEX_ARRAY);
|
||||
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
|
||||
glEnableClientState(GL_COLOR_ARRAY);
|
||||
glDisableClientState(GL_NORMAL_ARRAY);
|
||||
glEnable(GL_TEXTURE_2D);
|
||||
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
|
||||
glShadeModel(GL_SMOOTH);
|
||||
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
|
||||
|
||||
// If you are using this code with non-legacy OpenGL header/contexts (which you should not, prefer using imgui_impl_opengl3.cpp!!),
|
||||
// you may need to backup/reset/restore other state, e.g. for current shader using the commented lines below.
|
||||
// (DO NOT MODIFY THIS FILE! Add the code in your calling function)
|
||||
// GLint last_program;
|
||||
// glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
|
||||
// glUseProgram(0);
|
||||
// ImGui_ImplOpenGL2_RenderDrawData(...);
|
||||
// glUseProgram(last_program)
|
||||
// There are potentially many more states you could need to clear/setup that we can't access from default headers.
|
||||
// e.g. glBindBuffer(GL_ARRAY_BUFFER, 0), glDisable(GL_TEXTURE_CUBE_MAP).
|
||||
|
||||
// Setup viewport, orthographic projection matrix
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
|
||||
GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height));
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glPushMatrix();
|
||||
glLoadIdentity();
|
||||
glOrtho(draw_data->DisplayPos.x, draw_data->DisplayPos.x + draw_data->DisplaySize.x, draw_data->DisplayPos.y + draw_data->DisplaySize.y, draw_data->DisplayPos.y, -1.0f, +1.0f);
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glPushMatrix();
|
||||
glLoadIdentity();
|
||||
}
|
||||
|
||||
// OpenGL2 Render function.
|
||||
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
|
||||
// This is in order to be able to run within an OpenGL engine that doesn't do so.
|
||||
void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data)
|
||||
{
|
||||
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
|
||||
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
|
||||
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
|
||||
if (fb_width == 0 || fb_height == 0)
|
||||
return;
|
||||
|
||||
// Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
|
||||
// (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
|
||||
if (draw_data->Textures != nullptr)
|
||||
for (ImTextureData* tex : *draw_data->Textures)
|
||||
if (tex->Status != ImTextureStatus_OK)
|
||||
ImGui_ImplOpenGL2_UpdateTexture(tex);
|
||||
|
||||
// Backup GL state
|
||||
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
|
||||
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
|
||||
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
|
||||
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
|
||||
GLint last_shade_model; glGetIntegerv(GL_SHADE_MODEL, &last_shade_model);
|
||||
GLint last_tex_env_mode; glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &last_tex_env_mode);
|
||||
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
|
||||
|
||||
// Setup desired GL state
|
||||
ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height);
|
||||
|
||||
// Will project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
|
||||
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
|
||||
|
||||
// Render command lists
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* draw_list = draw_data->CmdLists[n];
|
||||
const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
|
||||
const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
|
||||
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, pos)));
|
||||
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, uv)));
|
||||
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, col)));
|
||||
|
||||
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height);
|
||||
else
|
||||
pcmd->UserCallback(draw_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
|
||||
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
|
||||
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle (Y is inverted in OpenGL)
|
||||
glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y));
|
||||
|
||||
// Bind texture, Draw
|
||||
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID());
|
||||
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore modified GL state
|
||||
glDisableClientState(GL_COLOR_ARRAY);
|
||||
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
|
||||
glDisableClientState(GL_VERTEX_ARRAY);
|
||||
glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glPopMatrix();
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glPopMatrix();
|
||||
glPopAttrib();
|
||||
glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
|
||||
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
|
||||
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
|
||||
glShadeModel(last_shade_model);
|
||||
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, last_tex_env_mode);
|
||||
}
|
||||
|
||||
void ImGui_ImplOpenGL2_UpdateTexture(ImTextureData* tex)
|
||||
{
|
||||
if (tex->Status == ImTextureStatus_WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
//IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
|
||||
IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == nullptr);
|
||||
IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
|
||||
const void* pixels = tex->GetPixels();
|
||||
GLuint gl_texture_id = 0;
|
||||
|
||||
// Upload texture to graphics system
|
||||
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
|
||||
GLint last_texture;
|
||||
GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture));
|
||||
GL_CALL(glGenTextures(1, &gl_texture_id));
|
||||
GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_texture_id));
|
||||
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
|
||||
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
|
||||
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
|
||||
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
|
||||
GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
|
||||
GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
|
||||
|
||||
// Store identifiers
|
||||
tex->SetTexID((ImTextureID)(intptr_t)gl_texture_id);
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
|
||||
// Restore state
|
||||
GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture));
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantUpdates)
|
||||
{
|
||||
// Update selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
|
||||
GLint last_texture;
|
||||
GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture));
|
||||
|
||||
GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID;
|
||||
GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id));
|
||||
GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width));
|
||||
for (ImTextureRect& r : tex->Updates)
|
||||
GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y)));
|
||||
GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
|
||||
GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); // Restore state
|
||||
tex->SetStatus(ImTextureStatus_OK);
|
||||
}
|
||||
else if (tex->Status == ImTextureStatus_WantDestroy)
|
||||
{
|
||||
GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID;
|
||||
glDeleteTextures(1, &gl_tex_id);
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex->SetTexID(ImTextureID_Invalid);
|
||||
tex->SetStatus(ImTextureStatus_Destroyed);
|
||||
}
|
||||
}
|
||||
|
||||
bool ImGui_ImplOpenGL2_CreateDeviceObjects()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplOpenGL2_DestroyDeviceObjects()
|
||||
{
|
||||
for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
|
||||
if (tex->RefCount == 1)
|
||||
{
|
||||
tex->SetStatus(ImTextureStatus_WantDestroy);
|
||||
ImGui_ImplOpenGL2_UpdateTexture(tex);
|
||||
}
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,43 +0,0 @@
|
||||
// dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline)
|
||||
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
// Missing features or Issues:
|
||||
// [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
|
||||
// **Prefer using the code in imgui_impl_opengl3.cpp**
|
||||
// This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
|
||||
// If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
|
||||
// complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
|
||||
// confuse your GPU driver.
|
||||
// The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL2_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data);
|
||||
|
||||
// Called by Init/NewFrame/Shutdown
|
||||
IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL2_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
1038
source/thirdparty/imgui/backends/imgui_impl_opengl3.cpp
vendored
1038
source/thirdparty/imgui/backends/imgui_impl_opengl3.cpp
vendored
File diff suppressed because it is too large
Load Diff
@@ -1,68 +0,0 @@
|
||||
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
|
||||
// - Desktop GL: 2.x 3.x 4.x
|
||||
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
|
||||
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
|
||||
// [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!]
|
||||
// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
|
||||
|
||||
// About WebGL/ES:
|
||||
// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
|
||||
// - This is done automatically on iOS, Android and Emscripten targets.
|
||||
// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// About GLSL version:
|
||||
// The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string.
|
||||
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
|
||||
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr);
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
|
||||
|
||||
// (Optional) Called by Init/NewFrame/Shutdown
|
||||
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
|
||||
|
||||
// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually.
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex);
|
||||
|
||||
// Configuration flags to add in your imconfig file:
|
||||
//#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten)
|
||||
//#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android)
|
||||
|
||||
// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
|
||||
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
|
||||
&& !defined(IMGUI_IMPL_OPENGL_ES3)
|
||||
|
||||
// Try to detect GLES on matching platforms
|
||||
#if defined(__APPLE__)
|
||||
#include <TargetConditionals.h>
|
||||
#endif
|
||||
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
|
||||
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
|
||||
#elif defined(__EMSCRIPTEN__) || defined(__amigaos4__)
|
||||
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
|
||||
#else
|
||||
// Otherwise imgui_impl_opengl3_loader.h will be used.
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,922 +0,0 @@
|
||||
//-----------------------------------------------------------------------------
|
||||
// About imgui_impl_opengl3_loader.h:
|
||||
//
|
||||
// We embed our own OpenGL loader to not require user to provide their own or to have to use ours,
|
||||
// which proved to be endless problems for users.
|
||||
// Our loader is custom-generated, based on gl3w but automatically filtered to only include
|
||||
// enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small.
|
||||
//
|
||||
// YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY.
|
||||
// THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE.
|
||||
//
|
||||
// IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions):
|
||||
// IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCLUDING 'imgui_impl_opengl3_loader.h'
|
||||
// IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER.
|
||||
// (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS)
|
||||
// YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT.
|
||||
// BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp
|
||||
// WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT.
|
||||
//
|
||||
// Regenerate with:
|
||||
// python3 gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
|
||||
//
|
||||
// More info:
|
||||
// https://github.com/dearimgui/gl3w_stripped
|
||||
// https://github.com/ocornut/imgui/issues/4445
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/*
|
||||
* This file was generated with gl3w_gen.py, part of imgl3w
|
||||
* (hosted at https://github.com/dearimgui/gl3w_stripped)
|
||||
*
|
||||
* This is free and unencumbered software released into the public domain.
|
||||
*
|
||||
* Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
* distribute this software, either in source code form or as a compiled
|
||||
* binary, for any purpose, commercial or non-commercial, and by any
|
||||
* means.
|
||||
*
|
||||
* In jurisdictions that recognize copyright laws, the author or authors
|
||||
* of this software dedicate any and all copyright interest in the
|
||||
* software to the public domain. We make this dedication for the benefit
|
||||
* of the public at large and to the detriment of our heirs and
|
||||
* successors. We intend this dedication to be an overt act of
|
||||
* relinquishment in perpetuity of all present and future rights to this
|
||||
* software under copyright law.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef __gl3w_h_
|
||||
#define __gl3w_h_
|
||||
|
||||
// Adapted from KHR/khrplatform.h to avoid including entire file.
|
||||
#ifndef __khrplatform_h_
|
||||
typedef float khronos_float_t;
|
||||
typedef signed char khronos_int8_t;
|
||||
typedef unsigned char khronos_uint8_t;
|
||||
typedef signed short int khronos_int16_t;
|
||||
typedef unsigned short int khronos_uint16_t;
|
||||
#ifdef _WIN64
|
||||
typedef signed long long int khronos_intptr_t;
|
||||
typedef signed long long int khronos_ssize_t;
|
||||
#else
|
||||
typedef signed long int khronos_intptr_t;
|
||||
typedef signed long int khronos_ssize_t;
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER) && !defined(__clang__)
|
||||
typedef signed __int64 khronos_int64_t;
|
||||
typedef unsigned __int64 khronos_uint64_t;
|
||||
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
|
||||
#include <stdint.h>
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#else
|
||||
typedef signed long long khronos_int64_t;
|
||||
typedef unsigned long long khronos_uint64_t;
|
||||
#endif
|
||||
#endif // __khrplatform_h_
|
||||
|
||||
#ifndef __gl_glcorearb_h_
|
||||
#define __gl_glcorearb_h_ 1
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
** Copyright 2013-2020 The Khronos Group Inc.
|
||||
** SPDX-License-Identifier: MIT
|
||||
**
|
||||
** This header is generated from the Khronos OpenGL / OpenGL ES XML
|
||||
** API Registry. The current version of the Registry, generator scripts
|
||||
** used to make the header, and the header can be found at
|
||||
** https://github.com/KhronosGroup/OpenGL-Registry
|
||||
*/
|
||||
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN 1
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#endif
|
||||
#ifndef APIENTRY
|
||||
#define APIENTRY
|
||||
#endif
|
||||
#ifndef APIENTRYP
|
||||
#define APIENTRYP APIENTRY *
|
||||
#endif
|
||||
#ifndef GLAPI
|
||||
#define GLAPI extern
|
||||
#endif
|
||||
/* glcorearb.h is for use with OpenGL core profile implementations.
|
||||
** It should should be placed in the same directory as gl.h and
|
||||
** included as <GL/glcorearb.h>.
|
||||
**
|
||||
** glcorearb.h includes only APIs in the latest OpenGL core profile
|
||||
** implementation together with APIs in newer ARB extensions which
|
||||
** can be supported by the core profile. It does not, and never will
|
||||
** include functionality removed from the core profile, such as
|
||||
** fixed-function vertex and fragment processing.
|
||||
**
|
||||
** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or
|
||||
** <GL/glext.h> in the same source file.
|
||||
*/
|
||||
/* Generated C header for:
|
||||
* API: gl
|
||||
* Profile: core
|
||||
* Versions considered: .*
|
||||
* Versions emitted: .*
|
||||
* Default extensions included: glcore
|
||||
* Additional extensions included: _nomatch_^
|
||||
* Extensions removed: _nomatch_^
|
||||
*/
|
||||
#ifndef GL_VERSION_1_0
|
||||
typedef void GLvoid;
|
||||
typedef unsigned int GLenum;
|
||||
|
||||
typedef khronos_float_t GLfloat;
|
||||
typedef int GLint;
|
||||
typedef int GLsizei;
|
||||
typedef unsigned int GLbitfield;
|
||||
typedef double GLdouble;
|
||||
typedef unsigned int GLuint;
|
||||
typedef unsigned char GLboolean;
|
||||
typedef khronos_uint8_t GLubyte;
|
||||
#define GL_COLOR_BUFFER_BIT 0x00004000
|
||||
#define GL_FALSE 0
|
||||
#define GL_TRUE 1
|
||||
#define GL_TRIANGLES 0x0004
|
||||
#define GL_ONE 1
|
||||
#define GL_SRC_ALPHA 0x0302
|
||||
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
|
||||
#define GL_FRONT 0x0404
|
||||
#define GL_BACK 0x0405
|
||||
#define GL_FRONT_AND_BACK 0x0408
|
||||
#define GL_POLYGON_MODE 0x0B40
|
||||
#define GL_CULL_FACE 0x0B44
|
||||
#define GL_DEPTH_TEST 0x0B71
|
||||
#define GL_STENCIL_TEST 0x0B90
|
||||
#define GL_VIEWPORT 0x0BA2
|
||||
#define GL_BLEND 0x0BE2
|
||||
#define GL_SCISSOR_BOX 0x0C10
|
||||
#define GL_SCISSOR_TEST 0x0C11
|
||||
#define GL_UNPACK_ROW_LENGTH 0x0CF2
|
||||
#define GL_PACK_ALIGNMENT 0x0D05
|
||||
#define GL_MAX_TEXTURE_SIZE 0x0D33
|
||||
#define GL_TEXTURE_2D 0x0DE1
|
||||
#define GL_UNSIGNED_BYTE 0x1401
|
||||
#define GL_UNSIGNED_SHORT 0x1403
|
||||
#define GL_UNSIGNED_INT 0x1405
|
||||
#define GL_FLOAT 0x1406
|
||||
#define GL_RGBA 0x1908
|
||||
#define GL_FILL 0x1B02
|
||||
#define GL_VENDOR 0x1F00
|
||||
#define GL_RENDERER 0x1F01
|
||||
#define GL_VERSION 0x1F02
|
||||
#define GL_EXTENSIONS 0x1F03
|
||||
#define GL_LINEAR 0x2601
|
||||
#define GL_TEXTURE_MAG_FILTER 0x2800
|
||||
#define GL_TEXTURE_MIN_FILTER 0x2801
|
||||
#define GL_TEXTURE_WRAP_S 0x2802
|
||||
#define GL_TEXTURE_WRAP_T 0x2803
|
||||
#define GL_REPEAT 0x2901
|
||||
typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
|
||||
typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
|
||||
typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
|
||||
typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
|
||||
typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
|
||||
typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
|
||||
typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap);
|
||||
typedef void (APIENTRYP PFNGLFLUSHPROC) (void);
|
||||
typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
|
||||
typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
|
||||
typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void);
|
||||
typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
|
||||
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
|
||||
typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
|
||||
typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
|
||||
GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
|
||||
GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
|
||||
GLAPI void APIENTRY glClear (GLbitfield mask);
|
||||
GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
|
||||
GLAPI void APIENTRY glDisable (GLenum cap);
|
||||
GLAPI void APIENTRY glEnable (GLenum cap);
|
||||
GLAPI void APIENTRY glFlush (void);
|
||||
GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
|
||||
GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
|
||||
GLAPI GLenum APIENTRY glGetError (void);
|
||||
GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data);
|
||||
GLAPI const GLubyte *APIENTRY glGetString (GLenum name);
|
||||
GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
|
||||
GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_0 */
|
||||
#ifndef GL_VERSION_1_1
|
||||
typedef khronos_float_t GLclampf;
|
||||
typedef double GLclampd;
|
||||
#define GL_TEXTURE_BINDING_2D 0x8069
|
||||
typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
|
||||
typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
|
||||
typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
|
||||
typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
|
||||
typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
|
||||
GLAPI void APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
|
||||
GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
|
||||
GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
|
||||
GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_1 */
|
||||
#ifndef GL_VERSION_1_2
|
||||
#define GL_CLAMP_TO_EDGE 0x812F
|
||||
#endif /* GL_VERSION_1_2 */
|
||||
#ifndef GL_VERSION_1_3
|
||||
#define GL_TEXTURE0 0x84C0
|
||||
#define GL_ACTIVE_TEXTURE 0x84E0
|
||||
typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glActiveTexture (GLenum texture);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_3 */
|
||||
#ifndef GL_VERSION_1_4
|
||||
#define GL_BLEND_DST_RGB 0x80C8
|
||||
#define GL_BLEND_SRC_RGB 0x80C9
|
||||
#define GL_BLEND_DST_ALPHA 0x80CA
|
||||
#define GL_BLEND_SRC_ALPHA 0x80CB
|
||||
#define GL_FUNC_ADD 0x8006
|
||||
typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
|
||||
typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
|
||||
GLAPI void APIENTRY glBlendEquation (GLenum mode);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_4 */
|
||||
#ifndef GL_VERSION_1_5
|
||||
typedef khronos_ssize_t GLsizeiptr;
|
||||
typedef khronos_intptr_t GLintptr;
|
||||
#define GL_ARRAY_BUFFER 0x8892
|
||||
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
|
||||
#define GL_ARRAY_BUFFER_BINDING 0x8894
|
||||
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
|
||||
#define GL_STREAM_DRAW 0x88E0
|
||||
typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
|
||||
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
|
||||
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
|
||||
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
|
||||
typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
|
||||
GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
|
||||
GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
|
||||
GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
|
||||
GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_5 */
|
||||
#ifndef GL_VERSION_2_0
|
||||
typedef char GLchar;
|
||||
typedef khronos_int16_t GLshort;
|
||||
typedef khronos_int8_t GLbyte;
|
||||
typedef khronos_uint16_t GLushort;
|
||||
#define GL_BLEND_EQUATION_RGB 0x8009
|
||||
#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
|
||||
#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
|
||||
#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
|
||||
#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
|
||||
#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
|
||||
#define GL_BLEND_EQUATION_ALPHA 0x883D
|
||||
#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
|
||||
#define GL_FRAGMENT_SHADER 0x8B30
|
||||
#define GL_VERTEX_SHADER 0x8B31
|
||||
#define GL_COMPILE_STATUS 0x8B81
|
||||
#define GL_LINK_STATUS 0x8B82
|
||||
#define GL_INFO_LOG_LENGTH 0x8B84
|
||||
#define GL_CURRENT_PROGRAM 0x8B8D
|
||||
#define GL_UPPER_LEFT 0x8CA2
|
||||
typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
|
||||
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
|
||||
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
|
||||
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
|
||||
typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
|
||||
typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
|
||||
typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
|
||||
typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
|
||||
typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
|
||||
typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
|
||||
typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
|
||||
typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
|
||||
typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
|
||||
typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
|
||||
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
|
||||
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
|
||||
typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
|
||||
typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
|
||||
typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
|
||||
typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
|
||||
typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
|
||||
typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
|
||||
typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
|
||||
GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
|
||||
GLAPI void APIENTRY glCompileShader (GLuint shader);
|
||||
GLAPI GLuint APIENTRY glCreateProgram (void);
|
||||
GLAPI GLuint APIENTRY glCreateShader (GLenum type);
|
||||
GLAPI void APIENTRY glDeleteProgram (GLuint program);
|
||||
GLAPI void APIENTRY glDeleteShader (GLuint shader);
|
||||
GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
|
||||
GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);
|
||||
GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
|
||||
GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
|
||||
GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
|
||||
GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
|
||||
GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
|
||||
GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
|
||||
GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);
|
||||
GLAPI GLboolean APIENTRY glIsProgram (GLuint program);
|
||||
GLAPI void APIENTRY glLinkProgram (GLuint program);
|
||||
GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
|
||||
GLAPI void APIENTRY glUseProgram (GLuint program);
|
||||
GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
|
||||
GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
|
||||
GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
|
||||
#endif
|
||||
#endif /* GL_VERSION_2_0 */
|
||||
#ifndef GL_VERSION_2_1
|
||||
#define GL_PIXEL_UNPACK_BUFFER 0x88EC
|
||||
#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF
|
||||
#endif /* GL_VERSION_2_1 */
|
||||
#ifndef GL_VERSION_3_0
|
||||
typedef khronos_uint16_t GLhalf;
|
||||
#define GL_MAJOR_VERSION 0x821B
|
||||
#define GL_MINOR_VERSION 0x821C
|
||||
#define GL_NUM_EXTENSIONS 0x821D
|
||||
#define GL_FRAMEBUFFER_SRGB 0x8DB9
|
||||
#define GL_VERTEX_ARRAY_BINDING 0x85B5
|
||||
typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
|
||||
typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
|
||||
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
|
||||
typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
|
||||
typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
|
||||
typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);
|
||||
GLAPI void APIENTRY glBindVertexArray (GLuint array);
|
||||
GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
|
||||
GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
|
||||
#endif
|
||||
#endif /* GL_VERSION_3_0 */
|
||||
#ifndef GL_VERSION_3_1
|
||||
#define GL_VERSION_3_1 1
|
||||
#define GL_PRIMITIVE_RESTART 0x8F9D
|
||||
#endif /* GL_VERSION_3_1 */
|
||||
#ifndef GL_VERSION_3_2
|
||||
#define GL_VERSION_3_2 1
|
||||
typedef struct __GLsync *GLsync;
|
||||
typedef khronos_uint64_t GLuint64;
|
||||
typedef khronos_int64_t GLint64;
|
||||
#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
|
||||
#define GL_CONTEXT_PROFILE_MASK 0x9126
|
||||
typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
|
||||
typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
|
||||
#endif
|
||||
#endif /* GL_VERSION_3_2 */
|
||||
#ifndef GL_VERSION_3_3
|
||||
#define GL_VERSION_3_3 1
|
||||
#define GL_SAMPLER_BINDING 0x8919
|
||||
typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
|
||||
#endif
|
||||
#endif /* GL_VERSION_3_3 */
|
||||
#ifndef GL_VERSION_4_1
|
||||
typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
|
||||
typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
|
||||
#endif /* GL_VERSION_4_1 */
|
||||
#ifndef GL_VERSION_4_3
|
||||
typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
|
||||
#endif /* GL_VERSION_4_3 */
|
||||
#ifndef GL_VERSION_4_5
|
||||
#define GL_CLIP_ORIGIN 0x935C
|
||||
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param);
|
||||
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param);
|
||||
#endif /* GL_VERSION_4_5 */
|
||||
#ifndef GL_ARB_bindless_texture
|
||||
typedef khronos_uint64_t GLuint64EXT;
|
||||
#endif /* GL_ARB_bindless_texture */
|
||||
#ifndef GL_ARB_cl_event
|
||||
struct _cl_context;
|
||||
struct _cl_event;
|
||||
#endif /* GL_ARB_cl_event */
|
||||
#ifndef GL_ARB_clip_control
|
||||
#define GL_ARB_clip_control 1
|
||||
#endif /* GL_ARB_clip_control */
|
||||
#ifndef GL_ARB_debug_output
|
||||
typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
|
||||
#endif /* GL_ARB_debug_output */
|
||||
#ifndef GL_EXT_EGL_image_storage
|
||||
typedef void *GLeglImageOES;
|
||||
#endif /* GL_EXT_EGL_image_storage */
|
||||
#ifndef GL_EXT_direct_state_access
|
||||
typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);
|
||||
typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);
|
||||
typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);
|
||||
typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);
|
||||
typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);
|
||||
#endif /* GL_EXT_direct_state_access */
|
||||
#ifndef GL_NV_draw_vulkan_image
|
||||
typedef void (APIENTRY *GLVULKANPROCNV)(void);
|
||||
#endif /* GL_NV_draw_vulkan_image */
|
||||
#ifndef GL_NV_gpu_shader5
|
||||
typedef khronos_int64_t GLint64EXT;
|
||||
#endif /* GL_NV_gpu_shader5 */
|
||||
#ifndef GL_NV_vertex_buffer_unified_memory
|
||||
typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
|
||||
#endif /* GL_NV_vertex_buffer_unified_memory */
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef GL3W_API
|
||||
#define GL3W_API
|
||||
#endif
|
||||
|
||||
#ifndef __gl_h_
|
||||
#define __gl_h_
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define GL3W_OK 0
|
||||
#define GL3W_ERROR_INIT -1
|
||||
#define GL3W_ERROR_LIBRARY_OPEN -2
|
||||
#define GL3W_ERROR_OPENGL_VERSION -3
|
||||
|
||||
typedef void (*GL3WglProc)(void);
|
||||
typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc);
|
||||
|
||||
/* gl3w api */
|
||||
GL3W_API int imgl3wInit(void);
|
||||
GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc);
|
||||
GL3W_API int imgl3wIsSupported(int major, int minor);
|
||||
GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
|
||||
|
||||
/* gl3w internal state */
|
||||
union ImGL3WProcs {
|
||||
GL3WglProc ptr[60];
|
||||
struct {
|
||||
PFNGLACTIVETEXTUREPROC ActiveTexture;
|
||||
PFNGLATTACHSHADERPROC AttachShader;
|
||||
PFNGLBINDBUFFERPROC BindBuffer;
|
||||
PFNGLBINDSAMPLERPROC BindSampler;
|
||||
PFNGLBINDTEXTUREPROC BindTexture;
|
||||
PFNGLBINDVERTEXARRAYPROC BindVertexArray;
|
||||
PFNGLBLENDEQUATIONPROC BlendEquation;
|
||||
PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate;
|
||||
PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate;
|
||||
PFNGLBUFFERDATAPROC BufferData;
|
||||
PFNGLBUFFERSUBDATAPROC BufferSubData;
|
||||
PFNGLCLEARPROC Clear;
|
||||
PFNGLCLEARCOLORPROC ClearColor;
|
||||
PFNGLCOMPILESHADERPROC CompileShader;
|
||||
PFNGLCREATEPROGRAMPROC CreateProgram;
|
||||
PFNGLCREATESHADERPROC CreateShader;
|
||||
PFNGLDELETEBUFFERSPROC DeleteBuffers;
|
||||
PFNGLDELETEPROGRAMPROC DeleteProgram;
|
||||
PFNGLDELETESHADERPROC DeleteShader;
|
||||
PFNGLDELETETEXTURESPROC DeleteTextures;
|
||||
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
|
||||
PFNGLDETACHSHADERPROC DetachShader;
|
||||
PFNGLDISABLEPROC Disable;
|
||||
PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray;
|
||||
PFNGLDRAWELEMENTSPROC DrawElements;
|
||||
PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex;
|
||||
PFNGLENABLEPROC Enable;
|
||||
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
|
||||
PFNGLFLUSHPROC Flush;
|
||||
PFNGLGENBUFFERSPROC GenBuffers;
|
||||
PFNGLGENTEXTURESPROC GenTextures;
|
||||
PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
|
||||
PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
|
||||
PFNGLGETERRORPROC GetError;
|
||||
PFNGLGETINTEGERVPROC GetIntegerv;
|
||||
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
|
||||
PFNGLGETPROGRAMIVPROC GetProgramiv;
|
||||
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
|
||||
PFNGLGETSHADERIVPROC GetShaderiv;
|
||||
PFNGLGETSTRINGPROC GetString;
|
||||
PFNGLGETSTRINGIPROC GetStringi;
|
||||
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
|
||||
PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv;
|
||||
PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv;
|
||||
PFNGLISENABLEDPROC IsEnabled;
|
||||
PFNGLISPROGRAMPROC IsProgram;
|
||||
PFNGLLINKPROGRAMPROC LinkProgram;
|
||||
PFNGLPIXELSTOREIPROC PixelStorei;
|
||||
PFNGLPOLYGONMODEPROC PolygonMode;
|
||||
PFNGLREADPIXELSPROC ReadPixels;
|
||||
PFNGLSCISSORPROC Scissor;
|
||||
PFNGLSHADERSOURCEPROC ShaderSource;
|
||||
PFNGLTEXIMAGE2DPROC TexImage2D;
|
||||
PFNGLTEXPARAMETERIPROC TexParameteri;
|
||||
PFNGLTEXSUBIMAGE2DPROC TexSubImage2D;
|
||||
PFNGLUNIFORM1IPROC Uniform1i;
|
||||
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
|
||||
PFNGLUSEPROGRAMPROC UseProgram;
|
||||
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
|
||||
PFNGLVIEWPORTPROC Viewport;
|
||||
} gl;
|
||||
};
|
||||
|
||||
GL3W_API extern union ImGL3WProcs imgl3wProcs;
|
||||
|
||||
/* OpenGL functions */
|
||||
#define glActiveTexture imgl3wProcs.gl.ActiveTexture
|
||||
#define glAttachShader imgl3wProcs.gl.AttachShader
|
||||
#define glBindBuffer imgl3wProcs.gl.BindBuffer
|
||||
#define glBindSampler imgl3wProcs.gl.BindSampler
|
||||
#define glBindTexture imgl3wProcs.gl.BindTexture
|
||||
#define glBindVertexArray imgl3wProcs.gl.BindVertexArray
|
||||
#define glBlendEquation imgl3wProcs.gl.BlendEquation
|
||||
#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate
|
||||
#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate
|
||||
#define glBufferData imgl3wProcs.gl.BufferData
|
||||
#define glBufferSubData imgl3wProcs.gl.BufferSubData
|
||||
#define glClear imgl3wProcs.gl.Clear
|
||||
#define glClearColor imgl3wProcs.gl.ClearColor
|
||||
#define glCompileShader imgl3wProcs.gl.CompileShader
|
||||
#define glCreateProgram imgl3wProcs.gl.CreateProgram
|
||||
#define glCreateShader imgl3wProcs.gl.CreateShader
|
||||
#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers
|
||||
#define glDeleteProgram imgl3wProcs.gl.DeleteProgram
|
||||
#define glDeleteShader imgl3wProcs.gl.DeleteShader
|
||||
#define glDeleteTextures imgl3wProcs.gl.DeleteTextures
|
||||
#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays
|
||||
#define glDetachShader imgl3wProcs.gl.DetachShader
|
||||
#define glDisable imgl3wProcs.gl.Disable
|
||||
#define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray
|
||||
#define glDrawElements imgl3wProcs.gl.DrawElements
|
||||
#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex
|
||||
#define glEnable imgl3wProcs.gl.Enable
|
||||
#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray
|
||||
#define glFlush imgl3wProcs.gl.Flush
|
||||
#define glGenBuffers imgl3wProcs.gl.GenBuffers
|
||||
#define glGenTextures imgl3wProcs.gl.GenTextures
|
||||
#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays
|
||||
#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation
|
||||
#define glGetError imgl3wProcs.gl.GetError
|
||||
#define glGetIntegerv imgl3wProcs.gl.GetIntegerv
|
||||
#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog
|
||||
#define glGetProgramiv imgl3wProcs.gl.GetProgramiv
|
||||
#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog
|
||||
#define glGetShaderiv imgl3wProcs.gl.GetShaderiv
|
||||
#define glGetString imgl3wProcs.gl.GetString
|
||||
#define glGetStringi imgl3wProcs.gl.GetStringi
|
||||
#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation
|
||||
#define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv
|
||||
#define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv
|
||||
#define glIsEnabled imgl3wProcs.gl.IsEnabled
|
||||
#define glIsProgram imgl3wProcs.gl.IsProgram
|
||||
#define glLinkProgram imgl3wProcs.gl.LinkProgram
|
||||
#define glPixelStorei imgl3wProcs.gl.PixelStorei
|
||||
#define glPolygonMode imgl3wProcs.gl.PolygonMode
|
||||
#define glReadPixels imgl3wProcs.gl.ReadPixels
|
||||
#define glScissor imgl3wProcs.gl.Scissor
|
||||
#define glShaderSource imgl3wProcs.gl.ShaderSource
|
||||
#define glTexImage2D imgl3wProcs.gl.TexImage2D
|
||||
#define glTexParameteri imgl3wProcs.gl.TexParameteri
|
||||
#define glTexSubImage2D imgl3wProcs.gl.TexSubImage2D
|
||||
#define glUniform1i imgl3wProcs.gl.Uniform1i
|
||||
#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv
|
||||
#define glUseProgram imgl3wProcs.gl.UseProgram
|
||||
#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer
|
||||
#define glViewport imgl3wProcs.gl.Viewport
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef IMGL3W_IMPL
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
|
||||
|
||||
#if defined(_WIN32)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN 1
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
static HMODULE libgl;
|
||||
typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR);
|
||||
static GL3WglGetProcAddr wgl_get_proc_address;
|
||||
|
||||
static int open_libgl(void)
|
||||
{
|
||||
libgl = LoadLibraryA("opengl32.dll");
|
||||
if (!libgl)
|
||||
return GL3W_ERROR_LIBRARY_OPEN;
|
||||
wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress");
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static void close_libgl(void) { FreeLibrary(libgl); }
|
||||
static GL3WglProc get_proc(const char *proc)
|
||||
{
|
||||
GL3WglProc res;
|
||||
res = (GL3WglProc)wgl_get_proc_address(proc);
|
||||
if (!res)
|
||||
res = (GL3WglProc)GetProcAddress(libgl, proc);
|
||||
return res;
|
||||
}
|
||||
#elif defined(__APPLE__)
|
||||
#include <dlfcn.h>
|
||||
|
||||
static void *libgl;
|
||||
static int open_libgl(void)
|
||||
{
|
||||
libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
|
||||
if (!libgl)
|
||||
return GL3W_ERROR_LIBRARY_OPEN;
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static void close_libgl(void) { dlclose(libgl); }
|
||||
|
||||
static GL3WglProc get_proc(const char *proc)
|
||||
{
|
||||
GL3WglProc res;
|
||||
*(void **)(&res) = dlsym(libgl, proc);
|
||||
return res;
|
||||
}
|
||||
#else
|
||||
#include <dlfcn.h>
|
||||
|
||||
static void* libgl; // OpenGL library
|
||||
static void* libglx; // GLX library
|
||||
static void* libegl; // EGL library
|
||||
static GL3WGetProcAddressProc gl_get_proc_address;
|
||||
|
||||
static void close_libgl(void)
|
||||
{
|
||||
if (libgl) {
|
||||
dlclose(libgl);
|
||||
libgl = NULL;
|
||||
}
|
||||
if (libegl) {
|
||||
dlclose(libegl);
|
||||
libegl = NULL;
|
||||
}
|
||||
if (libglx) {
|
||||
dlclose(libglx);
|
||||
libglx = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static int is_library_loaded(const char* name, void** lib)
|
||||
{
|
||||
*lib = dlopen(name, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
|
||||
return *lib != NULL;
|
||||
}
|
||||
|
||||
static int open_libs(void)
|
||||
{
|
||||
// On Linux we have two APIs to get process addresses: EGL and GLX.
|
||||
// EGL is supported under both X11 and Wayland, whereas GLX is X11-specific.
|
||||
|
||||
libgl = NULL;
|
||||
libegl = NULL;
|
||||
libglx = NULL;
|
||||
|
||||
// First check what's already loaded, the windowing library might have
|
||||
// already loaded either EGL or GLX and we want to use the same one.
|
||||
|
||||
if (is_library_loaded("libEGL.so.1", &libegl) ||
|
||||
is_library_loaded("libGLX.so.0", &libglx)) {
|
||||
libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
|
||||
if (libgl)
|
||||
return GL3W_OK;
|
||||
else
|
||||
close_libgl();
|
||||
}
|
||||
|
||||
if (is_library_loaded("libGL.so", &libgl))
|
||||
return GL3W_OK;
|
||||
if (is_library_loaded("libGL.so.1", &libgl))
|
||||
return GL3W_OK;
|
||||
if (is_library_loaded("libGL.so.3", &libgl))
|
||||
return GL3W_OK;
|
||||
|
||||
// Neither is already loaded, so we have to load one. Try EGL first
|
||||
// because it is supported under both X11 and Wayland.
|
||||
|
||||
// Load OpenGL + EGL
|
||||
libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
|
||||
libegl = dlopen("libEGL.so.1", RTLD_LAZY | RTLD_LOCAL);
|
||||
if (libgl && libegl)
|
||||
return GL3W_OK;
|
||||
else
|
||||
close_libgl();
|
||||
|
||||
// Fall back to legacy libGL, which includes GLX
|
||||
// While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983
|
||||
libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL);
|
||||
if (!libgl)
|
||||
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
|
||||
if (!libgl)
|
||||
libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL);
|
||||
|
||||
if (libgl)
|
||||
return GL3W_OK;
|
||||
|
||||
return GL3W_ERROR_LIBRARY_OPEN;
|
||||
}
|
||||
|
||||
static int open_libgl(void)
|
||||
{
|
||||
int res = open_libs();
|
||||
if (res)
|
||||
return res;
|
||||
|
||||
if (libegl)
|
||||
*(void**)(&gl_get_proc_address) = dlsym(libegl, "eglGetProcAddress");
|
||||
else if (libglx)
|
||||
*(void**)(&gl_get_proc_address) = dlsym(libglx, "glXGetProcAddressARB");
|
||||
else
|
||||
*(void**)(&gl_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
|
||||
|
||||
if (!gl_get_proc_address) {
|
||||
close_libgl();
|
||||
return GL3W_ERROR_LIBRARY_OPEN;
|
||||
}
|
||||
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static GL3WglProc get_proc(const char* proc)
|
||||
{
|
||||
GL3WglProc res = NULL;
|
||||
|
||||
// Before EGL version 1.5, eglGetProcAddress doesn't support querying core
|
||||
// functions and may return a dummy function if we try, so try to load the
|
||||
// function from the GL library directly first.
|
||||
if (libegl)
|
||||
*(void**)(&res) = dlsym(libgl, proc);
|
||||
|
||||
if (!res)
|
||||
res = gl_get_proc_address(proc);
|
||||
|
||||
if (!libegl && !res)
|
||||
*(void**)(&res) = dlsym(libgl, proc);
|
||||
|
||||
return res;
|
||||
}
|
||||
#endif
|
||||
|
||||
static struct { int major, minor; } version;
|
||||
|
||||
static int parse_version(void)
|
||||
{
|
||||
if (!glGetIntegerv)
|
||||
return GL3W_ERROR_INIT;
|
||||
glGetIntegerv(GL_MAJOR_VERSION, &version.major);
|
||||
glGetIntegerv(GL_MINOR_VERSION, &version.minor);
|
||||
if (version.major == 0 && version.minor == 0)
|
||||
{
|
||||
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
|
||||
if (const char* gl_version = (const char*)glGetString(GL_VERSION))
|
||||
sscanf(gl_version, "%d.%d", &version.major, &version.minor);
|
||||
}
|
||||
if (version.major < 2)
|
||||
return GL3W_ERROR_OPENGL_VERSION;
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static void load_procs(GL3WGetProcAddressProc proc);
|
||||
|
||||
int imgl3wInit(void)
|
||||
{
|
||||
int res = open_libgl();
|
||||
if (res)
|
||||
return res;
|
||||
atexit(close_libgl);
|
||||
return imgl3wInit2(get_proc);
|
||||
}
|
||||
|
||||
int imgl3wInit2(GL3WGetProcAddressProc proc)
|
||||
{
|
||||
load_procs(proc);
|
||||
return parse_version();
|
||||
}
|
||||
|
||||
int imgl3wIsSupported(int major, int minor)
|
||||
{
|
||||
if (major < 2)
|
||||
return 0;
|
||||
if (version.major == major)
|
||||
return version.minor >= minor;
|
||||
return version.major >= major;
|
||||
}
|
||||
|
||||
GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); }
|
||||
|
||||
static const char *proc_names[] = {
|
||||
"glActiveTexture",
|
||||
"glAttachShader",
|
||||
"glBindBuffer",
|
||||
"glBindSampler",
|
||||
"glBindTexture",
|
||||
"glBindVertexArray",
|
||||
"glBlendEquation",
|
||||
"glBlendEquationSeparate",
|
||||
"glBlendFuncSeparate",
|
||||
"glBufferData",
|
||||
"glBufferSubData",
|
||||
"glClear",
|
||||
"glClearColor",
|
||||
"glCompileShader",
|
||||
"glCreateProgram",
|
||||
"glCreateShader",
|
||||
"glDeleteBuffers",
|
||||
"glDeleteProgram",
|
||||
"glDeleteShader",
|
||||
"glDeleteTextures",
|
||||
"glDeleteVertexArrays",
|
||||
"glDetachShader",
|
||||
"glDisable",
|
||||
"glDisableVertexAttribArray",
|
||||
"glDrawElements",
|
||||
"glDrawElementsBaseVertex",
|
||||
"glEnable",
|
||||
"glEnableVertexAttribArray",
|
||||
"glFlush",
|
||||
"glGenBuffers",
|
||||
"glGenTextures",
|
||||
"glGenVertexArrays",
|
||||
"glGetAttribLocation",
|
||||
"glGetError",
|
||||
"glGetIntegerv",
|
||||
"glGetProgramInfoLog",
|
||||
"glGetProgramiv",
|
||||
"glGetShaderInfoLog",
|
||||
"glGetShaderiv",
|
||||
"glGetString",
|
||||
"glGetStringi",
|
||||
"glGetUniformLocation",
|
||||
"glGetVertexAttribPointerv",
|
||||
"glGetVertexAttribiv",
|
||||
"glIsEnabled",
|
||||
"glIsProgram",
|
||||
"glLinkProgram",
|
||||
"glPixelStorei",
|
||||
"glPolygonMode",
|
||||
"glReadPixels",
|
||||
"glScissor",
|
||||
"glShaderSource",
|
||||
"glTexImage2D",
|
||||
"glTexParameteri",
|
||||
"glTexSubImage2D",
|
||||
"glUniform1i",
|
||||
"glUniformMatrix4fv",
|
||||
"glUseProgram",
|
||||
"glVertexAttribPointer",
|
||||
"glViewport",
|
||||
};
|
||||
|
||||
GL3W_API union ImGL3WProcs imgl3wProcs;
|
||||
|
||||
static void load_procs(GL3WGetProcAddressProc proc)
|
||||
{
|
||||
size_t i;
|
||||
for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++)
|
||||
imgl3wProcs.ptr[i] = proc(proc_names[i]);
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,54 +0,0 @@
|
||||
// dear imgui: Platform Backend for OSX / Cocoa
|
||||
// This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..)
|
||||
// - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac.
|
||||
// - Requires linking with the GameController framework ("-framework GameController").
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend).
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/Pen.
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Gamepad support.
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// [X] Platform: IME support.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
#ifdef __OBJC__
|
||||
|
||||
@class NSEvent;
|
||||
@class NSView;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplOSX_Init(NSView* _Nonnull view);
|
||||
IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view);
|
||||
|
||||
#endif
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// C++ API
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS
|
||||
// #include <AppKit/AppKit.hpp>
|
||||
#ifndef __OBJC__
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view);
|
||||
IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view);
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
832
source/thirdparty/imgui/backends/imgui_impl_osx.mm
vendored
832
source/thirdparty/imgui/backends/imgui_impl_osx.mm
vendored
@@ -1,832 +0,0 @@
|
||||
// dear imgui: Platform Backend for OSX / Cocoa
|
||||
// This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..)
|
||||
// - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac.
|
||||
// - Requires linking with the GameController framework ("-framework GameController").
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend).
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/Pen.
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Gamepad support.
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// [X] Platform: IME support.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#import "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#import "imgui_impl_osx.h"
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <Carbon/Carbon.h>
|
||||
#import <GameController/GameController.h>
|
||||
#import <time.h>
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-27: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support.
|
||||
// 2025-06-12: ImGui_ImplOSX_HandleEvent() only process event for window containing our view. (#8644)
|
||||
// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set.
|
||||
// 2025-01-20: Removed notification observer when shutting down. (#8331)
|
||||
// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
|
||||
// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
|
||||
// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
|
||||
// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
|
||||
// 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library.
|
||||
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen.
|
||||
// 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen.
|
||||
// 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mice).
|
||||
// 2022-11-02: Fixed mouse coordinates before clicking the host window.
|
||||
// 2022-10-06: Fixed mouse inputs on flipped views.
|
||||
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
|
||||
// 2022-05-03: Inputs: Removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture.
|
||||
// 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
|
||||
// 2022-03-22: Inputs: Monitor NSKeyUp events to catch missing keyUp for key when user press Cmd + key
|
||||
// 2022-02-07: Inputs: Forward keyDown/keyUp events to OS when unused by dear imgui.
|
||||
// 2022-01-31: Fixed building with old Xcode versions that are missing gamepad features.
|
||||
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
|
||||
// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
|
||||
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
|
||||
// 2022-01-12: Inputs: Added basic Platform IME support, hooking the io.SetPlatformImeDataFn() function.
|
||||
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
|
||||
// 2021-12-13: *BREAKING CHANGE* Add NSView parameter to ImGui_ImplOSX_Init(). Generally fix keyboard support. Using kVK_* codes for keyboard keys.
|
||||
// 2021-12-13: Add game controller support.
|
||||
// 2021-09-21: Use mach_absolute_time as CFAbsoluteTimeGetCurrent can jump backwards.
|
||||
// 2021-08-17: Calling io.AddFocusEvent() on NSApplicationDidBecomeActiveNotification/NSApplicationDidResignActiveNotification events.
|
||||
// 2021-06-23: Inputs: Added a fix for shortcuts using CTRL key instead of CMD key.
|
||||
// 2021-04-19: Inputs: Added a fix for keys remaining stuck in pressed state when CMD-tabbing into different application.
|
||||
// 2021-01-27: Inputs: Added a fix for mouse position not being reported when mouse buttons other than left one are down.
|
||||
// 2020-10-28: Inputs: Added a fix for handling keypad-enter key.
|
||||
// 2020-05-25: Inputs: Added a fix for missing trackpad clicks when done with "soft tap".
|
||||
// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
|
||||
// 2019-10-11: Inputs: Fix using Backspace key.
|
||||
// 2019-07-21: Re-added clipboard handlers as they are not enabled by default in core imgui.cpp (reverted 2019-05-18 change).
|
||||
// 2019-05-28: Inputs: Added mouse cursor shape and visibility support.
|
||||
// 2019-05-18: Misc: Removed clipboard handlers as they are now supported by core imgui.cpp.
|
||||
// 2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range.
|
||||
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
|
||||
// 2018-07-07: Initial version.
|
||||
|
||||
#define APPLE_HAS_BUTTON_OPTIONS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 130000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500 || __TV_OS_VERSION_MIN_REQUIRED >= 130000)
|
||||
#define APPLE_HAS_CONTROLLER (__IPHONE_OS_VERSION_MIN_REQUIRED >= 140000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 110000 || __TV_OS_VERSION_MIN_REQUIRED >= 140000)
|
||||
#define APPLE_HAS_THUMBSTICKS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 120100 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101401 || __TV_OS_VERSION_MIN_REQUIRED >= 120100)
|
||||
|
||||
@class ImGuiObserver;
|
||||
@class KeyEventResponder;
|
||||
|
||||
// Data
|
||||
struct ImGui_ImplOSX_Data
|
||||
{
|
||||
CFTimeInterval Time;
|
||||
NSCursor* MouseCursors[ImGuiMouseCursor_COUNT];
|
||||
bool MouseCursorHidden;
|
||||
ImGuiObserver* Observer;
|
||||
KeyEventResponder* KeyEventResponder;
|
||||
NSTextInputContext* InputContext;
|
||||
id Monitor;
|
||||
NSWindow* Window;
|
||||
|
||||
ImGui_ImplOSX_Data() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
static ImGui_ImplOSX_Data* ImGui_ImplOSX_GetBackendData() { return (ImGui_ImplOSX_Data*)ImGui::GetIO().BackendPlatformUserData; }
|
||||
static void ImGui_ImplOSX_DestroyBackendData() { IM_DELETE(ImGui_ImplOSX_GetBackendData()); }
|
||||
|
||||
static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
|
||||
|
||||
// Forward Declarations
|
||||
static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view);
|
||||
static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view);
|
||||
|
||||
// Undocumented methods for creating cursors.
|
||||
@interface NSCursor()
|
||||
+ (id)_windowResizeNorthWestSouthEastCursor;
|
||||
+ (id)_windowResizeNorthEastSouthWestCursor;
|
||||
+ (id)_windowResizeNorthSouthCursor;
|
||||
+ (id)_windowResizeEastWestCursor;
|
||||
+ (id)busyButClickableCursor;
|
||||
@end
|
||||
|
||||
/**
|
||||
KeyEventResponder implements the NSTextInputClient protocol as is required by the macOS text input manager.
|
||||
|
||||
The macOS text input manager is invoked by calling the interpretKeyEvents method from the keyDown method.
|
||||
Keyboard events are then evaluated by the macOS input manager and valid text input is passed back via the
|
||||
insertText:replacementRange method.
|
||||
|
||||
This is the same approach employed by other cross-platform libraries such as SDL2:
|
||||
https://github.com/spurious/SDL-mirror/blob/e17aacbd09e65a4fd1e166621e011e581fb017a8/src/video/cocoa/SDL_cocoakeyboard.m#L53
|
||||
and GLFW:
|
||||
https://github.com/glfw/glfw/blob/b55a517ae0c7b5127dffa79a64f5406021bf9076/src/cocoa_window.m#L722-L723
|
||||
*/
|
||||
@interface KeyEventResponder: NSView<NSTextInputClient>
|
||||
@end
|
||||
|
||||
@implementation KeyEventResponder
|
||||
{
|
||||
float _posX;
|
||||
float _posY;
|
||||
NSRect _imeRect;
|
||||
}
|
||||
|
||||
#pragma mark - Public
|
||||
|
||||
- (void)setImePosX:(float)posX imePosY:(float)posY
|
||||
{
|
||||
_posX = posX;
|
||||
_posY = posY;
|
||||
}
|
||||
|
||||
- (void)updateImePosWithView:(NSView *)view
|
||||
{
|
||||
NSWindow* window = view.window;
|
||||
if (!window)
|
||||
return;
|
||||
NSRect contentRect = [window contentRectForFrameRect:window.frame];
|
||||
NSRect rect = NSMakeRect(_posX, contentRect.size.height - _posY, 0, 0);
|
||||
_imeRect = [window convertRectToScreen:rect];
|
||||
}
|
||||
|
||||
- (void)viewDidMoveToWindow
|
||||
{
|
||||
// Ensure self is a first responder to receive the input events.
|
||||
[self.window makeFirstResponder:self];
|
||||
}
|
||||
|
||||
- (void)keyDown:(NSEvent*)event
|
||||
{
|
||||
if (!ImGui_ImplOSX_HandleEvent(event, self))
|
||||
[super keyDown:event];
|
||||
|
||||
// Call to the macOS input manager system.
|
||||
[self interpretKeyEvents:@[event]];
|
||||
}
|
||||
|
||||
- (void)keyUp:(NSEvent*)event
|
||||
{
|
||||
if (!ImGui_ImplOSX_HandleEvent(event, self))
|
||||
[super keyUp:event];
|
||||
}
|
||||
|
||||
- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
NSString* characters;
|
||||
if ([aString isKindOfClass:[NSAttributedString class]])
|
||||
characters = [aString string];
|
||||
else
|
||||
characters = (NSString*)aString;
|
||||
|
||||
io.AddInputCharactersUTF8(characters.UTF8String);
|
||||
}
|
||||
|
||||
- (BOOL)acceptsFirstResponder
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)doCommandBySelector:(SEL)myselector
|
||||
{
|
||||
}
|
||||
|
||||
- (nullable NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range actualRange:(nullable NSRangePointer)actualRange
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (NSUInteger)characterIndexForPoint:(NSPoint)point
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(nullable NSRangePointer)actualRange
|
||||
{
|
||||
return _imeRect;
|
||||
}
|
||||
|
||||
- (BOOL)hasMarkedText
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (NSRange)markedRange
|
||||
{
|
||||
return NSMakeRange(NSNotFound, 0);
|
||||
}
|
||||
|
||||
- (NSRange)selectedRange
|
||||
{
|
||||
return NSMakeRange(NSNotFound, 0);
|
||||
}
|
||||
|
||||
- (void)setMarkedText:(nonnull id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
|
||||
{
|
||||
}
|
||||
|
||||
- (void)unmarkText
|
||||
{
|
||||
}
|
||||
|
||||
- (nonnull NSArray<NSAttributedStringKey>*)validAttributesForMarkedText
|
||||
{
|
||||
return @[];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface ImGuiObserver : NSObject
|
||||
|
||||
- (void)onApplicationBecomeActive:(NSNotification*)aNotification;
|
||||
- (void)onApplicationBecomeInactive:(NSNotification*)aNotification;
|
||||
|
||||
@end
|
||||
|
||||
@implementation ImGuiObserver
|
||||
|
||||
- (void)onApplicationBecomeActive:(NSNotification*)aNotification
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddFocusEvent(true);
|
||||
}
|
||||
|
||||
- (void)onApplicationBecomeInactive:(NSNotification*)aNotification
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddFocusEvent(false);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
// Functions
|
||||
|
||||
// Not static to allow third-party code to use that if they want to (but undocumented)
|
||||
ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code);
|
||||
ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code)
|
||||
{
|
||||
switch (key_code)
|
||||
{
|
||||
case kVK_ANSI_A: return ImGuiKey_A;
|
||||
case kVK_ANSI_S: return ImGuiKey_S;
|
||||
case kVK_ANSI_D: return ImGuiKey_D;
|
||||
case kVK_ANSI_F: return ImGuiKey_F;
|
||||
case kVK_ANSI_H: return ImGuiKey_H;
|
||||
case kVK_ANSI_G: return ImGuiKey_G;
|
||||
case kVK_ANSI_Z: return ImGuiKey_Z;
|
||||
case kVK_ANSI_X: return ImGuiKey_X;
|
||||
case kVK_ANSI_C: return ImGuiKey_C;
|
||||
case kVK_ANSI_V: return ImGuiKey_V;
|
||||
case kVK_ANSI_B: return ImGuiKey_B;
|
||||
case kVK_ANSI_Q: return ImGuiKey_Q;
|
||||
case kVK_ANSI_W: return ImGuiKey_W;
|
||||
case kVK_ANSI_E: return ImGuiKey_E;
|
||||
case kVK_ANSI_R: return ImGuiKey_R;
|
||||
case kVK_ANSI_Y: return ImGuiKey_Y;
|
||||
case kVK_ANSI_T: return ImGuiKey_T;
|
||||
case kVK_ANSI_1: return ImGuiKey_1;
|
||||
case kVK_ANSI_2: return ImGuiKey_2;
|
||||
case kVK_ANSI_3: return ImGuiKey_3;
|
||||
case kVK_ANSI_4: return ImGuiKey_4;
|
||||
case kVK_ANSI_6: return ImGuiKey_6;
|
||||
case kVK_ANSI_5: return ImGuiKey_5;
|
||||
case kVK_ANSI_Equal: return ImGuiKey_Equal;
|
||||
case kVK_ANSI_9: return ImGuiKey_9;
|
||||
case kVK_ANSI_7: return ImGuiKey_7;
|
||||
case kVK_ANSI_Minus: return ImGuiKey_Minus;
|
||||
case kVK_ANSI_8: return ImGuiKey_8;
|
||||
case kVK_ANSI_0: return ImGuiKey_0;
|
||||
case kVK_ANSI_RightBracket: return ImGuiKey_RightBracket;
|
||||
case kVK_ANSI_O: return ImGuiKey_O;
|
||||
case kVK_ANSI_U: return ImGuiKey_U;
|
||||
case kVK_ANSI_LeftBracket: return ImGuiKey_LeftBracket;
|
||||
case kVK_ANSI_I: return ImGuiKey_I;
|
||||
case kVK_ANSI_P: return ImGuiKey_P;
|
||||
case kVK_ANSI_L: return ImGuiKey_L;
|
||||
case kVK_ANSI_J: return ImGuiKey_J;
|
||||
case kVK_ANSI_Quote: return ImGuiKey_Apostrophe;
|
||||
case kVK_ANSI_K: return ImGuiKey_K;
|
||||
case kVK_ANSI_Semicolon: return ImGuiKey_Semicolon;
|
||||
case kVK_ANSI_Backslash: return ImGuiKey_Backslash;
|
||||
case kVK_ANSI_Comma: return ImGuiKey_Comma;
|
||||
case kVK_ANSI_Slash: return ImGuiKey_Slash;
|
||||
case kVK_ANSI_N: return ImGuiKey_N;
|
||||
case kVK_ANSI_M: return ImGuiKey_M;
|
||||
case kVK_ANSI_Period: return ImGuiKey_Period;
|
||||
case kVK_ANSI_Grave: return ImGuiKey_GraveAccent;
|
||||
case kVK_ANSI_KeypadDecimal: return ImGuiKey_KeypadDecimal;
|
||||
case kVK_ANSI_KeypadMultiply: return ImGuiKey_KeypadMultiply;
|
||||
case kVK_ANSI_KeypadPlus: return ImGuiKey_KeypadAdd;
|
||||
case kVK_ANSI_KeypadClear: return ImGuiKey_NumLock;
|
||||
case kVK_ANSI_KeypadDivide: return ImGuiKey_KeypadDivide;
|
||||
case kVK_ANSI_KeypadEnter: return ImGuiKey_KeypadEnter;
|
||||
case kVK_ANSI_KeypadMinus: return ImGuiKey_KeypadSubtract;
|
||||
case kVK_ANSI_KeypadEquals: return ImGuiKey_KeypadEqual;
|
||||
case kVK_ANSI_Keypad0: return ImGuiKey_Keypad0;
|
||||
case kVK_ANSI_Keypad1: return ImGuiKey_Keypad1;
|
||||
case kVK_ANSI_Keypad2: return ImGuiKey_Keypad2;
|
||||
case kVK_ANSI_Keypad3: return ImGuiKey_Keypad3;
|
||||
case kVK_ANSI_Keypad4: return ImGuiKey_Keypad4;
|
||||
case kVK_ANSI_Keypad5: return ImGuiKey_Keypad5;
|
||||
case kVK_ANSI_Keypad6: return ImGuiKey_Keypad6;
|
||||
case kVK_ANSI_Keypad7: return ImGuiKey_Keypad7;
|
||||
case kVK_ANSI_Keypad8: return ImGuiKey_Keypad8;
|
||||
case kVK_ANSI_Keypad9: return ImGuiKey_Keypad9;
|
||||
case kVK_Return: return ImGuiKey_Enter;
|
||||
case kVK_Tab: return ImGuiKey_Tab;
|
||||
case kVK_Space: return ImGuiKey_Space;
|
||||
case kVK_Delete: return ImGuiKey_Backspace;
|
||||
case kVK_Escape: return ImGuiKey_Escape;
|
||||
case kVK_CapsLock: return ImGuiKey_CapsLock;
|
||||
case kVK_Control: return ImGuiKey_LeftCtrl;
|
||||
case kVK_Shift: return ImGuiKey_LeftShift;
|
||||
case kVK_Option: return ImGuiKey_LeftAlt;
|
||||
case kVK_Command: return ImGuiKey_LeftSuper;
|
||||
case kVK_RightControl: return ImGuiKey_RightCtrl;
|
||||
case kVK_RightShift: return ImGuiKey_RightShift;
|
||||
case kVK_RightOption: return ImGuiKey_RightAlt;
|
||||
case kVK_RightCommand: return ImGuiKey_RightSuper;
|
||||
// case kVK_Function: return ImGuiKey_;
|
||||
// case kVK_VolumeUp: return ImGuiKey_;
|
||||
// case kVK_VolumeDown: return ImGuiKey_;
|
||||
// case kVK_Mute: return ImGuiKey_;
|
||||
case kVK_F1: return ImGuiKey_F1;
|
||||
case kVK_F2: return ImGuiKey_F2;
|
||||
case kVK_F3: return ImGuiKey_F3;
|
||||
case kVK_F4: return ImGuiKey_F4;
|
||||
case kVK_F5: return ImGuiKey_F5;
|
||||
case kVK_F6: return ImGuiKey_F6;
|
||||
case kVK_F7: return ImGuiKey_F7;
|
||||
case kVK_F8: return ImGuiKey_F8;
|
||||
case kVK_F9: return ImGuiKey_F9;
|
||||
case kVK_F10: return ImGuiKey_F10;
|
||||
case kVK_F11: return ImGuiKey_F11;
|
||||
case kVK_F12: return ImGuiKey_F12;
|
||||
case kVK_F13: return ImGuiKey_F13;
|
||||
case kVK_F14: return ImGuiKey_F14;
|
||||
case kVK_F15: return ImGuiKey_F15;
|
||||
case kVK_F16: return ImGuiKey_F16;
|
||||
case kVK_F17: return ImGuiKey_F17;
|
||||
case kVK_F18: return ImGuiKey_F18;
|
||||
case kVK_F19: return ImGuiKey_F19;
|
||||
case kVK_F20: return ImGuiKey_F20;
|
||||
case 0x6E: return ImGuiKey_Menu;
|
||||
case kVK_Help: return ImGuiKey_Insert;
|
||||
case kVK_Home: return ImGuiKey_Home;
|
||||
case kVK_PageUp: return ImGuiKey_PageUp;
|
||||
case kVK_ForwardDelete: return ImGuiKey_Delete;
|
||||
case kVK_End: return ImGuiKey_End;
|
||||
case kVK_PageDown: return ImGuiKey_PageDown;
|
||||
case kVK_LeftArrow: return ImGuiKey_LeftArrow;
|
||||
case kVK_RightArrow: return ImGuiKey_RightArrow;
|
||||
case kVK_DownArrow: return ImGuiKey_DownArrow;
|
||||
case kVK_UpArrow: return ImGuiKey_UpArrow;
|
||||
default: return ImGuiKey_None;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS
|
||||
|
||||
IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view) {
|
||||
return ImGui_ImplOSX_Init((__bridge NSView*)(view));
|
||||
}
|
||||
|
||||
IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view) {
|
||||
return ImGui_ImplOSX_NewFrame((__bridge NSView*)(view));
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
bool ImGui_ImplOSX_Init(NSView* view)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplOSX_Data* bd = IM_NEW(ImGui_ImplOSX_Data)();
|
||||
io.BackendPlatformUserData = (void*)bd;
|
||||
io.BackendPlatformName = "imgui_impl_osx";
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
|
||||
//io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
|
||||
|
||||
bd->Observer = [ImGuiObserver new];
|
||||
bd->Window = view.window ?: NSApp.orderedWindows.firstObject;
|
||||
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
|
||||
main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (__bridge_retained void*)bd->Window;
|
||||
|
||||
// Load cursors. Some of them are undocumented.
|
||||
bd->MouseCursorHidden = false;
|
||||
bd->MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_Wait] = bd->MouseCursors[ImGuiMouseCursor_Progress] = [NSCursor respondsToSelector:@selector(busyButClickableCursor)] ? [NSCursor busyButClickableCursor] : [NSCursor arrowCursor];
|
||||
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor];
|
||||
|
||||
// Note that imgui.cpp also include default OSX clipboard handlers which can be enabled
|
||||
// by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line.
|
||||
// Since we are already in ObjC land here, it is easy for us to add a clipboard handler using the NSPasteboard api.
|
||||
platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* str) -> void
|
||||
{
|
||||
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
|
||||
[pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil];
|
||||
[pasteboard setString:[NSString stringWithUTF8String:str] forType:NSPasteboardTypeString];
|
||||
};
|
||||
|
||||
platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) -> const char*
|
||||
{
|
||||
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
|
||||
NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]];
|
||||
if (![available isEqualToString:NSPasteboardTypeString])
|
||||
return nullptr;
|
||||
|
||||
NSString* string = [pasteboard stringForType:NSPasteboardTypeString];
|
||||
if (string == nil)
|
||||
return nullptr;
|
||||
|
||||
const char* string_c = (const char*)[string UTF8String];
|
||||
size_t string_len = strlen(string_c);
|
||||
static ImVector<char> s_clipboard;
|
||||
s_clipboard.resize((int)string_len + 1);
|
||||
strcpy(s_clipboard.Data, string_c);
|
||||
return s_clipboard.Data;
|
||||
};
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:bd->Observer
|
||||
selector:@selector(onApplicationBecomeActive:)
|
||||
name:NSApplicationDidBecomeActiveNotification
|
||||
object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:bd->Observer
|
||||
selector:@selector(onApplicationBecomeInactive:)
|
||||
name:NSApplicationDidResignActiveNotification
|
||||
object:nil];
|
||||
|
||||
// Add the NSTextInputClient to the view hierarchy,
|
||||
// to receive keyboard events and translate them to input text.
|
||||
bd->KeyEventResponder = [[KeyEventResponder alloc] initWithFrame:NSZeroRect];
|
||||
bd->InputContext = [[NSTextInputContext alloc] initWithClient:bd->KeyEventResponder];
|
||||
[view addSubview:bd->KeyEventResponder];
|
||||
ImGui_ImplOSX_AddTrackingArea(view);
|
||||
|
||||
platform_io.Platform_SetImeDataFn = [](ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data) -> void
|
||||
{
|
||||
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
|
||||
if (data->WantVisible)
|
||||
{
|
||||
[bd->InputContext activate];
|
||||
}
|
||||
else
|
||||
{
|
||||
[bd->InputContext discardMarkedText];
|
||||
[bd->InputContext invalidateCharacterCoordinates];
|
||||
[bd->InputContext deactivate];
|
||||
}
|
||||
[bd->KeyEventResponder setImePosX:data->InputPos.x imePosY:data->InputPos.y + data->InputLineHeight];
|
||||
};
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplOSX_Shutdown()
|
||||
{
|
||||
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
|
||||
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:bd->Observer];
|
||||
bd->Observer = nullptr;
|
||||
if (bd->Monitor != nullptr)
|
||||
{
|
||||
[NSEvent removeMonitor:bd->Monitor];
|
||||
bd->Monitor = nullptr;
|
||||
}
|
||||
|
||||
ImGui_ImplOSX_DestroyBackendData();
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendPlatformName = nullptr;
|
||||
io.BackendPlatformUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasGamepad);
|
||||
}
|
||||
|
||||
static void ImGui_ImplOSX_UpdateMouseCursor()
|
||||
{
|
||||
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
|
||||
return;
|
||||
|
||||
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
|
||||
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
|
||||
{
|
||||
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
|
||||
if (!bd->MouseCursorHidden)
|
||||
{
|
||||
bd->MouseCursorHidden = true;
|
||||
[NSCursor hide];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NSCursor* desired = bd->MouseCursors[imgui_cursor] ?: bd->MouseCursors[ImGuiMouseCursor_Arrow];
|
||||
// -[NSCursor set] generates measurable overhead if called unconditionally.
|
||||
if (desired != NSCursor.currentCursor)
|
||||
{
|
||||
[desired set];
|
||||
}
|
||||
if (bd->MouseCursorHidden)
|
||||
{
|
||||
bd->MouseCursorHidden = false;
|
||||
[NSCursor unhide];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ImGui_ImplOSX_UpdateGamepads()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
#if APPLE_HAS_CONTROLLER
|
||||
GCController* controller = GCController.current;
|
||||
#else
|
||||
GCController* controller = GCController.controllers.firstObject;
|
||||
#endif
|
||||
if (controller == nil || controller.extendedGamepad == nil)
|
||||
{
|
||||
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
|
||||
return;
|
||||
}
|
||||
|
||||
GCExtendedGamepad* gp = controller.extendedGamepad;
|
||||
|
||||
// Update gamepad inputs
|
||||
#define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V)
|
||||
#define MAP_BUTTON(KEY_NO, BUTTON_NAME) { io.AddKeyEvent(KEY_NO, gp.BUTTON_NAME.isPressed); }
|
||||
#define MAP_ANALOG(KEY_NO, AXIS_NAME, V0, V1) { float vn = (float)(gp.AXIS_NAME.value - V0) / (float)(V1 - V0); vn = IM_SATURATE(vn); io.AddKeyAnalogEvent(KEY_NO, vn > 0.1f, vn); }
|
||||
const float thumb_dead_zone = 0.0f;
|
||||
|
||||
#if APPLE_HAS_BUTTON_OPTIONS
|
||||
MAP_BUTTON(ImGuiKey_GamepadBack, buttonOptions);
|
||||
#endif
|
||||
MAP_BUTTON(ImGuiKey_GamepadFaceLeft, buttonX); // Xbox X, PS Square
|
||||
MAP_BUTTON(ImGuiKey_GamepadFaceRight, buttonB); // Xbox B, PS Circle
|
||||
MAP_BUTTON(ImGuiKey_GamepadFaceUp, buttonY); // Xbox Y, PS Triangle
|
||||
MAP_BUTTON(ImGuiKey_GamepadFaceDown, buttonA); // Xbox A, PS Cross
|
||||
MAP_BUTTON(ImGuiKey_GamepadDpadLeft, dpad.left);
|
||||
MAP_BUTTON(ImGuiKey_GamepadDpadRight, dpad.right);
|
||||
MAP_BUTTON(ImGuiKey_GamepadDpadUp, dpad.up);
|
||||
MAP_BUTTON(ImGuiKey_GamepadDpadDown, dpad.down);
|
||||
MAP_ANALOG(ImGuiKey_GamepadL1, leftShoulder, 0.0f, 1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadR1, rightShoulder, 0.0f, 1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadL2, leftTrigger, 0.0f, 1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadR2, rightTrigger, 0.0f, 1.0f);
|
||||
#if APPLE_HAS_THUMBSTICKS
|
||||
MAP_BUTTON(ImGuiKey_GamepadL3, leftThumbstickButton);
|
||||
MAP_BUTTON(ImGuiKey_GamepadR3, rightThumbstickButton);
|
||||
#endif
|
||||
MAP_ANALOG(ImGuiKey_GamepadLStickLeft, leftThumbstick.xAxis, -thumb_dead_zone, -1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadLStickRight, leftThumbstick.xAxis, +thumb_dead_zone, +1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadLStickUp, leftThumbstick.yAxis, +thumb_dead_zone, +1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadLStickDown, leftThumbstick.yAxis, -thumb_dead_zone, -1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadRStickLeft, rightThumbstick.xAxis, -thumb_dead_zone, -1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadRStickRight, rightThumbstick.xAxis, +thumb_dead_zone, +1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadRStickUp, rightThumbstick.yAxis, +thumb_dead_zone, +1.0f);
|
||||
MAP_ANALOG(ImGuiKey_GamepadRStickDown, rightThumbstick.yAxis, -thumb_dead_zone, -1.0f);
|
||||
#undef MAP_BUTTON
|
||||
#undef MAP_ANALOG
|
||||
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
|
||||
}
|
||||
|
||||
static void ImGui_ImplOSX_UpdateImePosWithView(NSView* view)
|
||||
{
|
||||
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
if (io.WantTextInput)
|
||||
[bd->KeyEventResponder updateImePosWithView:view];
|
||||
}
|
||||
|
||||
void ImGui_ImplOSX_NewFrame(NSView* view)
|
||||
{
|
||||
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOSX_Init()?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Setup display size
|
||||
if (view)
|
||||
{
|
||||
const float dpi = (float)[view.window backingScaleFactor];
|
||||
io.DisplaySize = ImVec2((float)view.bounds.size.width, (float)view.bounds.size.height);
|
||||
io.DisplayFramebufferScale = ImVec2(dpi, dpi);
|
||||
}
|
||||
|
||||
// Setup time step
|
||||
if (bd->Time == 0.0)
|
||||
bd->Time = GetMachAbsoluteTimeInSeconds();
|
||||
|
||||
double current_time = GetMachAbsoluteTimeInSeconds();
|
||||
io.DeltaTime = (float)(current_time - bd->Time);
|
||||
bd->Time = current_time;
|
||||
|
||||
ImGui_ImplOSX_UpdateMouseCursor();
|
||||
ImGui_ImplOSX_UpdateGamepads();
|
||||
ImGui_ImplOSX_UpdateImePosWithView(view);
|
||||
}
|
||||
|
||||
// Must only be called for a mouse event, otherwise an exception occurs
|
||||
// (Note that NSEventTypeScrollWheel is considered "other input". Oddly enough an exception does not occur with it, but the value will sometimes be wrong!)
|
||||
static ImGuiMouseSource GetMouseSource(NSEvent* event)
|
||||
{
|
||||
switch (event.subtype)
|
||||
{
|
||||
case NSEventSubtypeTabletPoint:
|
||||
return ImGuiMouseSource_Pen;
|
||||
// macOS considers input from relative touch devices (like the trackpad or Apple Magic Mouse) to be touch input.
|
||||
// This doesn't really make sense for Dear ImGui, which expects absolute touch devices only.
|
||||
// There does not seem to be a simple way to disambiguate things here so we consider NSEventSubtypeTouch events to always come from mice.
|
||||
// See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html#//apple_ref/doc/uid/10000060i-CH13-SW24
|
||||
//case NSEventSubtypeTouch:
|
||||
// return ImGuiMouseSource_TouchScreen;
|
||||
case NSEventSubtypeMouseEvent:
|
||||
default:
|
||||
return ImGuiMouseSource_Mouse;
|
||||
}
|
||||
}
|
||||
|
||||
static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view)
|
||||
{
|
||||
// Only process events from the window containing ImGui view
|
||||
if (event.window != view.window)
|
||||
return false;
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown)
|
||||
{
|
||||
int button = (int)[event buttonNumber];
|
||||
if (button >= 0 && button < ImGuiMouseButton_COUNT)
|
||||
{
|
||||
io.AddMouseSourceEvent(GetMouseSource(event));
|
||||
io.AddMouseButtonEvent(button, true);
|
||||
}
|
||||
return io.WantCaptureMouse;
|
||||
}
|
||||
|
||||
if (event.type == NSEventTypeLeftMouseUp || event.type == NSEventTypeRightMouseUp || event.type == NSEventTypeOtherMouseUp)
|
||||
{
|
||||
int button = (int)[event buttonNumber];
|
||||
if (button >= 0 && button < ImGuiMouseButton_COUNT)
|
||||
{
|
||||
io.AddMouseSourceEvent(GetMouseSource(event));
|
||||
io.AddMouseButtonEvent(button, false);
|
||||
}
|
||||
return io.WantCaptureMouse;
|
||||
}
|
||||
|
||||
if (event.type == NSEventTypeMouseMoved || event.type == NSEventTypeLeftMouseDragged || event.type == NSEventTypeRightMouseDragged || event.type == NSEventTypeOtherMouseDragged)
|
||||
{
|
||||
NSPoint mousePoint = event.locationInWindow;
|
||||
if (event.window == nil)
|
||||
mousePoint = [[view window] convertPointFromScreen:mousePoint];
|
||||
mousePoint = [view convertPoint:mousePoint fromView:nil];
|
||||
if ([view isFlipped])
|
||||
mousePoint = NSMakePoint(mousePoint.x, mousePoint.y);
|
||||
else
|
||||
mousePoint = NSMakePoint(mousePoint.x, view.bounds.size.height - mousePoint.y);
|
||||
io.AddMouseSourceEvent(GetMouseSource(event));
|
||||
io.AddMousePosEvent((float)mousePoint.x, (float)mousePoint.y);
|
||||
return io.WantCaptureMouse;
|
||||
}
|
||||
|
||||
if (event.type == NSEventTypeScrollWheel)
|
||||
{
|
||||
// Ignore canceled events.
|
||||
//
|
||||
// From macOS 12.1, scrolling with two fingers and then decelerating
|
||||
// by tapping two fingers results in two events appearing:
|
||||
//
|
||||
// 1. A scroll wheel NSEvent, with a phase == NSEventPhaseMayBegin, when the user taps
|
||||
// two fingers to decelerate or stop the scroll events.
|
||||
//
|
||||
// 2. A scroll wheel NSEvent, with a phase == NSEventPhaseCancelled, when the user releases the
|
||||
// two-finger tap. It is this event that sometimes contains large values for scrollingDeltaX and
|
||||
// scrollingDeltaY. When these are added to the current x and y positions of the scrolling view,
|
||||
// it appears to jump up or down. It can be observed in Preview, various JetBrains IDEs and here.
|
||||
if (event.phase == NSEventPhaseCancelled)
|
||||
return false;
|
||||
|
||||
double wheel_dx = 0.0;
|
||||
double wheel_dy = 0.0;
|
||||
|
||||
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
|
||||
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
|
||||
{
|
||||
wheel_dx = [event scrollingDeltaX];
|
||||
wheel_dy = [event scrollingDeltaY];
|
||||
if ([event hasPreciseScrollingDeltas])
|
||||
{
|
||||
wheel_dx *= 0.01;
|
||||
wheel_dy *= 0.01;
|
||||
}
|
||||
}
|
||||
else
|
||||
#endif // MAC_OS_X_VERSION_MAX_ALLOWED
|
||||
{
|
||||
wheel_dx = [event deltaX] * 0.1;
|
||||
wheel_dy = [event deltaY] * 0.1;
|
||||
}
|
||||
if (wheel_dx != 0.0 || wheel_dy != 0.0)
|
||||
io.AddMouseWheelEvent((float)wheel_dx, (float)wheel_dy);
|
||||
|
||||
return io.WantCaptureMouse;
|
||||
}
|
||||
|
||||
if (event.type == NSEventTypeKeyDown || event.type == NSEventTypeKeyUp)
|
||||
{
|
||||
if ([event isARepeat])
|
||||
return io.WantCaptureKeyboard;
|
||||
|
||||
int key_code = (int)[event keyCode];
|
||||
ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code);
|
||||
io.AddKeyEvent(key, event.type == NSEventTypeKeyDown);
|
||||
io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code)
|
||||
|
||||
return io.WantCaptureKeyboard;
|
||||
}
|
||||
|
||||
if (event.type == NSEventTypeFlagsChanged)
|
||||
{
|
||||
unsigned short key_code = [event keyCode];
|
||||
NSEventModifierFlags modifier_flags = [event modifierFlags];
|
||||
|
||||
io.AddKeyEvent(ImGuiMod_Shift, (modifier_flags & NSEventModifierFlagShift) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Ctrl, (modifier_flags & NSEventModifierFlagControl) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Alt, (modifier_flags & NSEventModifierFlagOption) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Super, (modifier_flags & NSEventModifierFlagCommand) != 0);
|
||||
|
||||
ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code);
|
||||
if (key != ImGuiKey_None)
|
||||
{
|
||||
// macOS does not generate down/up event for modifiers. We're trying
|
||||
// to use hardware dependent masks to extract that information.
|
||||
// 'imgui_mask' is left as a fallback.
|
||||
NSEventModifierFlags mask = 0;
|
||||
switch (key)
|
||||
{
|
||||
case ImGuiKey_LeftCtrl: mask = 0x0001; break;
|
||||
case ImGuiKey_RightCtrl: mask = 0x2000; break;
|
||||
case ImGuiKey_LeftShift: mask = 0x0002; break;
|
||||
case ImGuiKey_RightShift: mask = 0x0004; break;
|
||||
case ImGuiKey_LeftSuper: mask = 0x0008; break;
|
||||
case ImGuiKey_RightSuper: mask = 0x0010; break;
|
||||
case ImGuiKey_LeftAlt: mask = 0x0020; break;
|
||||
case ImGuiKey_RightAlt: mask = 0x0040; break;
|
||||
default:
|
||||
return io.WantCaptureKeyboard;
|
||||
}
|
||||
io.AddKeyEvent(key, (modifier_flags & mask) != 0);
|
||||
io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code)
|
||||
}
|
||||
|
||||
return io.WantCaptureKeyboard;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view)
|
||||
{
|
||||
// If we want to receive key events, we either need to be in the responder chain of the key view,
|
||||
// or else we can install a local monitor. The consequence of this heavy-handed approach is that
|
||||
// we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our
|
||||
// window, we'd want to be much more careful than just ingesting the complete event stream.
|
||||
// To match the behavior of other backends, we pass every event down to the OS.
|
||||
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
|
||||
if (bd->Monitor)
|
||||
return;
|
||||
NSEventMask eventMask = 0;
|
||||
eventMask |= NSEventMaskMouseMoved | NSEventMaskScrollWheel;
|
||||
eventMask |= NSEventMaskLeftMouseDown | NSEventMaskLeftMouseUp | NSEventMaskLeftMouseDragged;
|
||||
eventMask |= NSEventMaskRightMouseDown | NSEventMaskRightMouseUp | NSEventMaskRightMouseDragged;
|
||||
eventMask |= NSEventMaskOtherMouseDown | NSEventMaskOtherMouseUp | NSEventMaskOtherMouseDragged;
|
||||
eventMask |= NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
|
||||
bd->Monitor = [NSEvent addLocalMonitorForEventsMatchingMask:eventMask
|
||||
handler:^NSEvent* _Nullable(NSEvent* event)
|
||||
{
|
||||
ImGui_ImplOSX_HandleEvent(event, view);
|
||||
return event;
|
||||
}];
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
893
source/thirdparty/imgui/backends/imgui_impl_sdl2.cpp
vendored
893
source/thirdparty/imgui/backends/imgui_impl_sdl2.cpp
vendored
@@ -1,893 +0,0 @@
|
||||
// dear imgui: Platform Backend for SDL2
|
||||
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
|
||||
// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
|
||||
// (Prefer SDL 2.0.5+ for full feature support.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Clipboard support.
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Gamepad support.
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-11: Added ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) and ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) helper to facilitate making DPI-aware apps.
|
||||
// 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561)
|
||||
// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set.
|
||||
// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468)
|
||||
// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650)
|
||||
// 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode.
|
||||
// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support.
|
||||
// 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler.
|
||||
// 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array.
|
||||
// 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f.
|
||||
// 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190)
|
||||
// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
|
||||
// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
|
||||
// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
|
||||
// - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn
|
||||
// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
|
||||
// 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*.
|
||||
// 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853)
|
||||
// 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions.
|
||||
// 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library.
|
||||
// 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode().
|
||||
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
|
||||
// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
|
||||
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
|
||||
// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
|
||||
// 2023-02-07: Implement IME handler (io.SetPlatformImeDataFn will call SDL_SetTextInputRect()/SDL_StartTextInput()).
|
||||
// 2023-02-07: *BREAKING CHANGE* Renamed this backend file from imgui_impl_sdl.cpp/.h to imgui_impl_sdl2.cpp/.h in prevision for the future release of SDL3.
|
||||
// 2023-02-02: Avoid calling SDL_SetCursor() when cursor has not changed, as the function is surprisingly costly on Mac with latest SDL (may be fixed in next SDL version).
|
||||
// 2023-02-02: Added support for SDL 2.0.18+ preciseX/preciseY mouse wheel data for smooth scrolling + Scaling X value on Emscripten (bug?). (#4019, #6096)
|
||||
// 2023-02-02: Removed SDL_MOUSEWHEEL value clamping, as values seem correct in latest Emscripten. (#4019)
|
||||
// 2023-02-01: Flipping SDL_MOUSEWHEEL 'wheel.x' value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463)
|
||||
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
|
||||
// 2022-09-26: Inputs: Disable SDL 2.0.22 new "auto capture" (SDL_HINT_MOUSE_AUTO_CAPTURE) which prevents drag and drop across windows for multi-viewport support + don't capture when drag and dropping. (#5710)
|
||||
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
|
||||
// 2022-03-22: Inputs: Fix mouse position issues when dragging outside of boundaries. SDL_CaptureMouse() erroneously still gives out LEAVE events when hovering OS decorations.
|
||||
// 2022-03-22: Inputs: Added support for extra mouse buttons (SDL_BUTTON_X1/SDL_BUTTON_X2).
|
||||
// 2022-02-04: Added SDL_Renderer* parameter to ImGui_ImplSDL2_InitForSDLRenderer(), so we can use SDL_GetRendererOutputSize() instead of SDL_GL_GetDrawableSize() when bound to a SDL_Renderer.
|
||||
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
|
||||
// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
|
||||
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
|
||||
// 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
|
||||
// 2022-01-12: Update mouse inputs using SDL_MOUSEMOTION/SDL_WINDOWEVENT_LEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API.
|
||||
// 2022-01-12: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted.
|
||||
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
|
||||
// 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST.
|
||||
// 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+)
|
||||
// 2021-06-29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950)
|
||||
// 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends.
|
||||
// 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2).
|
||||
// 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state).
|
||||
// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
|
||||
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
|
||||
// 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
|
||||
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
|
||||
// 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls.
|
||||
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
|
||||
// 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'.
|
||||
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
|
||||
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
|
||||
// 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
|
||||
// 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
|
||||
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
|
||||
// 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
|
||||
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
|
||||
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
|
||||
// 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
|
||||
// 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
|
||||
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
|
||||
// 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS.
|
||||
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
|
||||
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
|
||||
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_sdl2.h"
|
||||
|
||||
// Clang warnings with -Weverything
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
|
||||
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
|
||||
#endif
|
||||
|
||||
// SDL
|
||||
#include <SDL.h>
|
||||
#include <SDL_syswm.h>
|
||||
#include <stdio.h> // for snprintf()
|
||||
#ifdef __APPLE__
|
||||
#include <TargetConditionals.h>
|
||||
#endif
|
||||
#ifdef __EMSCRIPTEN__
|
||||
#include <emscripten/em_js.h>
|
||||
#endif
|
||||
#undef Status // X11 headers are leaking this.
|
||||
|
||||
#if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
|
||||
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
|
||||
#else
|
||||
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
|
||||
#endif
|
||||
#define SDL_HAS_PER_MONITOR_DPI SDL_VERSION_ATLEAST(2,0,4)
|
||||
#define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
|
||||
#define SDL_HAS_OPEN_URL SDL_VERSION_ATLEAST(2,0,14)
|
||||
#if SDL_HAS_VULKAN
|
||||
#include <SDL_vulkan.h>
|
||||
#endif
|
||||
|
||||
// SDL Data
|
||||
struct ImGui_ImplSDL2_Data
|
||||
{
|
||||
SDL_Window* Window;
|
||||
Uint32 WindowID;
|
||||
SDL_Renderer* Renderer;
|
||||
Uint64 Time;
|
||||
char* ClipboardTextData;
|
||||
char BackendPlatformName[48];
|
||||
|
||||
// Mouse handling
|
||||
Uint32 MouseWindowID;
|
||||
int MouseButtonsDown;
|
||||
SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
|
||||
SDL_Cursor* MouseLastCursor;
|
||||
int MouseLastLeaveFrame;
|
||||
bool MouseCanUseGlobalState;
|
||||
bool MouseCanUseCapture;
|
||||
|
||||
// Gamepad handling
|
||||
ImVector<SDL_GameController*> Gamepads;
|
||||
ImGui_ImplSDL2_GamepadMode GamepadMode;
|
||||
bool WantUpdateGamepadsList;
|
||||
|
||||
ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
|
||||
// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
|
||||
static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
|
||||
}
|
||||
|
||||
// Functions
|
||||
static const char* ImGui_ImplSDL2_GetClipboardText(ImGuiContext*)
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
if (bd->ClipboardTextData)
|
||||
SDL_free(bd->ClipboardTextData);
|
||||
bd->ClipboardTextData = SDL_GetClipboardText();
|
||||
return bd->ClipboardTextData;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_SetClipboardText(ImGuiContext*, const char* text)
|
||||
{
|
||||
SDL_SetClipboardText(text);
|
||||
}
|
||||
|
||||
// Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow().
|
||||
static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data)
|
||||
{
|
||||
if (data->WantVisible)
|
||||
{
|
||||
SDL_Rect r;
|
||||
r.x = (int)data->InputPos.x;
|
||||
r.y = (int)data->InputPos.y;
|
||||
r.w = 1;
|
||||
r.h = (int)data->InputLineHeight;
|
||||
SDL_SetTextInputRect(&r);
|
||||
}
|
||||
}
|
||||
|
||||
// Not static to allow third-party code to use that if they want to (but undocumented)
|
||||
ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
|
||||
ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
|
||||
{
|
||||
switch (keycode)
|
||||
{
|
||||
case SDLK_TAB: return ImGuiKey_Tab;
|
||||
case SDLK_LEFT: return ImGuiKey_LeftArrow;
|
||||
case SDLK_RIGHT: return ImGuiKey_RightArrow;
|
||||
case SDLK_UP: return ImGuiKey_UpArrow;
|
||||
case SDLK_DOWN: return ImGuiKey_DownArrow;
|
||||
case SDLK_PAGEUP: return ImGuiKey_PageUp;
|
||||
case SDLK_PAGEDOWN: return ImGuiKey_PageDown;
|
||||
case SDLK_HOME: return ImGuiKey_Home;
|
||||
case SDLK_END: return ImGuiKey_End;
|
||||
case SDLK_INSERT: return ImGuiKey_Insert;
|
||||
case SDLK_DELETE: return ImGuiKey_Delete;
|
||||
case SDLK_BACKSPACE: return ImGuiKey_Backspace;
|
||||
case SDLK_SPACE: return ImGuiKey_Space;
|
||||
case SDLK_RETURN: return ImGuiKey_Enter;
|
||||
case SDLK_ESCAPE: return ImGuiKey_Escape;
|
||||
//case SDLK_QUOTE: return ImGuiKey_Apostrophe;
|
||||
case SDLK_COMMA: return ImGuiKey_Comma;
|
||||
//case SDLK_MINUS: return ImGuiKey_Minus;
|
||||
case SDLK_PERIOD: return ImGuiKey_Period;
|
||||
//case SDLK_SLASH: return ImGuiKey_Slash;
|
||||
case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
|
||||
//case SDLK_EQUALS: return ImGuiKey_Equal;
|
||||
//case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
|
||||
//case SDLK_BACKSLASH: return ImGuiKey_Backslash;
|
||||
//case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
|
||||
//case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent;
|
||||
case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
|
||||
case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
|
||||
case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
|
||||
case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen;
|
||||
case SDLK_PAUSE: return ImGuiKey_Pause;
|
||||
case SDLK_KP_0: return ImGuiKey_Keypad0;
|
||||
case SDLK_KP_1: return ImGuiKey_Keypad1;
|
||||
case SDLK_KP_2: return ImGuiKey_Keypad2;
|
||||
case SDLK_KP_3: return ImGuiKey_Keypad3;
|
||||
case SDLK_KP_4: return ImGuiKey_Keypad4;
|
||||
case SDLK_KP_5: return ImGuiKey_Keypad5;
|
||||
case SDLK_KP_6: return ImGuiKey_Keypad6;
|
||||
case SDLK_KP_7: return ImGuiKey_Keypad7;
|
||||
case SDLK_KP_8: return ImGuiKey_Keypad8;
|
||||
case SDLK_KP_9: return ImGuiKey_Keypad9;
|
||||
case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal;
|
||||
case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide;
|
||||
case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
|
||||
case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract;
|
||||
case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd;
|
||||
case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter;
|
||||
case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual;
|
||||
case SDLK_LCTRL: return ImGuiKey_LeftCtrl;
|
||||
case SDLK_LSHIFT: return ImGuiKey_LeftShift;
|
||||
case SDLK_LALT: return ImGuiKey_LeftAlt;
|
||||
case SDLK_LGUI: return ImGuiKey_LeftSuper;
|
||||
case SDLK_RCTRL: return ImGuiKey_RightCtrl;
|
||||
case SDLK_RSHIFT: return ImGuiKey_RightShift;
|
||||
case SDLK_RALT: return ImGuiKey_RightAlt;
|
||||
case SDLK_RGUI: return ImGuiKey_RightSuper;
|
||||
case SDLK_APPLICATION: return ImGuiKey_Menu;
|
||||
case SDLK_0: return ImGuiKey_0;
|
||||
case SDLK_1: return ImGuiKey_1;
|
||||
case SDLK_2: return ImGuiKey_2;
|
||||
case SDLK_3: return ImGuiKey_3;
|
||||
case SDLK_4: return ImGuiKey_4;
|
||||
case SDLK_5: return ImGuiKey_5;
|
||||
case SDLK_6: return ImGuiKey_6;
|
||||
case SDLK_7: return ImGuiKey_7;
|
||||
case SDLK_8: return ImGuiKey_8;
|
||||
case SDLK_9: return ImGuiKey_9;
|
||||
case SDLK_a: return ImGuiKey_A;
|
||||
case SDLK_b: return ImGuiKey_B;
|
||||
case SDLK_c: return ImGuiKey_C;
|
||||
case SDLK_d: return ImGuiKey_D;
|
||||
case SDLK_e: return ImGuiKey_E;
|
||||
case SDLK_f: return ImGuiKey_F;
|
||||
case SDLK_g: return ImGuiKey_G;
|
||||
case SDLK_h: return ImGuiKey_H;
|
||||
case SDLK_i: return ImGuiKey_I;
|
||||
case SDLK_j: return ImGuiKey_J;
|
||||
case SDLK_k: return ImGuiKey_K;
|
||||
case SDLK_l: return ImGuiKey_L;
|
||||
case SDLK_m: return ImGuiKey_M;
|
||||
case SDLK_n: return ImGuiKey_N;
|
||||
case SDLK_o: return ImGuiKey_O;
|
||||
case SDLK_p: return ImGuiKey_P;
|
||||
case SDLK_q: return ImGuiKey_Q;
|
||||
case SDLK_r: return ImGuiKey_R;
|
||||
case SDLK_s: return ImGuiKey_S;
|
||||
case SDLK_t: return ImGuiKey_T;
|
||||
case SDLK_u: return ImGuiKey_U;
|
||||
case SDLK_v: return ImGuiKey_V;
|
||||
case SDLK_w: return ImGuiKey_W;
|
||||
case SDLK_x: return ImGuiKey_X;
|
||||
case SDLK_y: return ImGuiKey_Y;
|
||||
case SDLK_z: return ImGuiKey_Z;
|
||||
case SDLK_F1: return ImGuiKey_F1;
|
||||
case SDLK_F2: return ImGuiKey_F2;
|
||||
case SDLK_F3: return ImGuiKey_F3;
|
||||
case SDLK_F4: return ImGuiKey_F4;
|
||||
case SDLK_F5: return ImGuiKey_F5;
|
||||
case SDLK_F6: return ImGuiKey_F6;
|
||||
case SDLK_F7: return ImGuiKey_F7;
|
||||
case SDLK_F8: return ImGuiKey_F8;
|
||||
case SDLK_F9: return ImGuiKey_F9;
|
||||
case SDLK_F10: return ImGuiKey_F10;
|
||||
case SDLK_F11: return ImGuiKey_F11;
|
||||
case SDLK_F12: return ImGuiKey_F12;
|
||||
case SDLK_F13: return ImGuiKey_F13;
|
||||
case SDLK_F14: return ImGuiKey_F14;
|
||||
case SDLK_F15: return ImGuiKey_F15;
|
||||
case SDLK_F16: return ImGuiKey_F16;
|
||||
case SDLK_F17: return ImGuiKey_F17;
|
||||
case SDLK_F18: return ImGuiKey_F18;
|
||||
case SDLK_F19: return ImGuiKey_F19;
|
||||
case SDLK_F20: return ImGuiKey_F20;
|
||||
case SDLK_F21: return ImGuiKey_F21;
|
||||
case SDLK_F22: return ImGuiKey_F22;
|
||||
case SDLK_F23: return ImGuiKey_F23;
|
||||
case SDLK_F24: return ImGuiKey_F24;
|
||||
case SDLK_AC_BACK: return ImGuiKey_AppBack;
|
||||
case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
|
||||
default: break;
|
||||
}
|
||||
|
||||
// Fallback to scancode
|
||||
switch (scancode)
|
||||
{
|
||||
case SDL_SCANCODE_GRAVE: return ImGuiKey_GraveAccent;
|
||||
case SDL_SCANCODE_MINUS: return ImGuiKey_Minus;
|
||||
case SDL_SCANCODE_EQUALS: return ImGuiKey_Equal;
|
||||
case SDL_SCANCODE_LEFTBRACKET: return ImGuiKey_LeftBracket;
|
||||
case SDL_SCANCODE_RIGHTBRACKET: return ImGuiKey_RightBracket;
|
||||
case SDL_SCANCODE_NONUSBACKSLASH: return ImGuiKey_Oem102;
|
||||
case SDL_SCANCODE_BACKSLASH: return ImGuiKey_Backslash;
|
||||
case SDL_SCANCODE_SEMICOLON: return ImGuiKey_Semicolon;
|
||||
case SDL_SCANCODE_APOSTROPHE: return ImGuiKey_Apostrophe;
|
||||
case SDL_SCANCODE_COMMA: return ImGuiKey_Comma;
|
||||
case SDL_SCANCODE_PERIOD: return ImGuiKey_Period;
|
||||
case SDL_SCANCODE_SLASH: return ImGuiKey_Slash;
|
||||
default: break;
|
||||
}
|
||||
return ImGuiKey_None;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);
|
||||
}
|
||||
|
||||
static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id)
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr;
|
||||
}
|
||||
|
||||
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
|
||||
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
|
||||
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
|
||||
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
|
||||
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
|
||||
bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
switch (event->type)
|
||||
{
|
||||
case SDL_MOUSEMOTION:
|
||||
{
|
||||
if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == nullptr)
|
||||
return false;
|
||||
ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
|
||||
io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
|
||||
io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);
|
||||
return true;
|
||||
}
|
||||
case SDL_MOUSEWHEEL:
|
||||
{
|
||||
if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == nullptr)
|
||||
return false;
|
||||
//IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
|
||||
#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!
|
||||
float wheel_x = -event->wheel.preciseX;
|
||||
float wheel_y = event->wheel.preciseY;
|
||||
#else
|
||||
float wheel_x = -(float)event->wheel.x;
|
||||
float wheel_y = (float)event->wheel.y;
|
||||
#endif
|
||||
#if defined(__EMSCRIPTEN__) && !SDL_VERSION_ATLEAST(2,31,0)
|
||||
wheel_x /= 100.0f;
|
||||
#endif
|
||||
io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
|
||||
io.AddMouseWheelEvent(wheel_x, wheel_y);
|
||||
return true;
|
||||
}
|
||||
case SDL_MOUSEBUTTONDOWN:
|
||||
case SDL_MOUSEBUTTONUP:
|
||||
{
|
||||
if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == nullptr)
|
||||
return false;
|
||||
int mouse_button = -1;
|
||||
if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
|
||||
if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }
|
||||
if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }
|
||||
if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }
|
||||
if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }
|
||||
if (mouse_button == -1)
|
||||
break;
|
||||
io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
|
||||
io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));
|
||||
bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));
|
||||
return true;
|
||||
}
|
||||
case SDL_TEXTINPUT:
|
||||
{
|
||||
if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == nullptr)
|
||||
return false;
|
||||
io.AddInputCharactersUTF8(event->text.text);
|
||||
return true;
|
||||
}
|
||||
case SDL_KEYDOWN:
|
||||
case SDL_KEYUP:
|
||||
{
|
||||
if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == nullptr)
|
||||
return false;
|
||||
ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);
|
||||
//IMGUI_DEBUG_LOG("SDL_KEY_%s : key=%d ('%s'), scancode=%d ('%s'), mod=%X\n",
|
||||
// (event->type == SDL_KEYDOWN) ? "DOWN" : "UP ", event->key.keysym.sym, SDL_GetKeyName(event->key.keysym.sym), event->key.keysym.scancode, SDL_GetScancodeName(event->key.keysym.scancode), event->key.keysym.mod);
|
||||
ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);
|
||||
io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));
|
||||
io.SetKeyEventNativeData(key, (int)event->key.keysym.sym, (int)event->key.keysym.scancode, (int)event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
|
||||
return true;
|
||||
}
|
||||
case SDL_WINDOWEVENT:
|
||||
{
|
||||
if (ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID) == nullptr)
|
||||
return false;
|
||||
// - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.
|
||||
// - However we won't get a correct LEAVE event for a captured window.
|
||||
// - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
|
||||
// causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why
|
||||
// we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.
|
||||
Uint8 window_event = event->window.event;
|
||||
if (window_event == SDL_WINDOWEVENT_ENTER)
|
||||
{
|
||||
bd->MouseWindowID = event->window.windowID;
|
||||
bd->MouseLastLeaveFrame = 0;
|
||||
}
|
||||
if (window_event == SDL_WINDOWEVENT_LEAVE)
|
||||
bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;
|
||||
if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)
|
||||
io.AddFocusEvent(true);
|
||||
else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)
|
||||
io.AddFocusEvent(false);
|
||||
return true;
|
||||
}
|
||||
case SDL_CONTROLLERDEVICEADDED:
|
||||
case SDL_CONTROLLERDEVICEREMOVED:
|
||||
{
|
||||
bd->WantUpdateGamepadsList = true;
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef __EMSCRIPTEN__
|
||||
EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); });
|
||||
#endif
|
||||
|
||||
static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
|
||||
|
||||
// Obtain compiled and runtime versions
|
||||
SDL_version ver_compiled;
|
||||
SDL_version ver_runtime;
|
||||
SDL_VERSION(&ver_compiled);
|
||||
SDL_GetVersion(&ver_runtime);
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)();
|
||||
snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl2 (%u.%u.%u, %u.%u.%u)",
|
||||
ver_compiled.major, ver_compiled.minor, ver_compiled.patch, ver_runtime.major, ver_runtime.minor, ver_runtime.patch);
|
||||
io.BackendPlatformUserData = (void*)bd;
|
||||
io.BackendPlatformName = bd->BackendPlatformName;
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
|
||||
|
||||
bd->Window = window;
|
||||
bd->WindowID = SDL_GetWindowID(window);
|
||||
bd->Renderer = renderer;
|
||||
|
||||
// Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse()
|
||||
// ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
|
||||
bd->MouseCanUseGlobalState = false;
|
||||
bd->MouseCanUseCapture = false;
|
||||
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
|
||||
const char* sdl_backend = SDL_GetCurrentVideoDriver();
|
||||
const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
|
||||
for (const char* item : capture_and_global_state_whitelist)
|
||||
if (strncmp(sdl_backend, item, strlen(item)) == 0)
|
||||
bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true;
|
||||
#endif
|
||||
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
|
||||
platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
|
||||
platform_io.Platform_ClipboardUserData = nullptr;
|
||||
platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData;
|
||||
#ifdef __EMSCRIPTEN__
|
||||
platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; };
|
||||
#elif SDL_HAS_OPEN_URL
|
||||
platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; };
|
||||
#endif
|
||||
|
||||
// Gamepad handling
|
||||
bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst;
|
||||
bd->WantUpdateGamepadsList = true;
|
||||
|
||||
// Load mouse cursors
|
||||
bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
|
||||
bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
|
||||
bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
|
||||
bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT);
|
||||
bd->MouseCursors[ImGuiMouseCursor_Progress] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAITARROW);
|
||||
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO);
|
||||
|
||||
// Set platform dependent data in viewport
|
||||
// Our mouse update function expect PlatformHandle to be filled for the main viewport
|
||||
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
|
||||
main_viewport->PlatformHandle = (void*)(intptr_t)bd->WindowID;
|
||||
main_viewport->PlatformHandleRaw = nullptr;
|
||||
SDL_SysWMinfo info;
|
||||
SDL_VERSION(&info.version);
|
||||
if (SDL_GetWindowWMInfo(window, &info))
|
||||
{
|
||||
#if defined(SDL_VIDEO_DRIVER_WINDOWS)
|
||||
main_viewport->PlatformHandleRaw = (void*)info.info.win.window;
|
||||
#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
|
||||
main_viewport->PlatformHandleRaw = (void*)info.info.cocoa.window;
|
||||
#endif
|
||||
}
|
||||
|
||||
// From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
|
||||
// Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
|
||||
// (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application.
|
||||
// It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click:
|
||||
// you can ignore SDL_MOUSEBUTTONDOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED)
|
||||
#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH
|
||||
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
|
||||
#endif
|
||||
|
||||
// From 2.0.18: Enable native IME.
|
||||
// IMPORTANT: This is used at the time of SDL_CreateWindow() so this will only affects secondary windows, if any.
|
||||
// For the main window to be affected, your application needs to call this manually before calling SDL_CreateWindow().
|
||||
#ifdef SDL_HINT_IME_SHOW_UI
|
||||
SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
|
||||
#endif
|
||||
|
||||
// From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710)
|
||||
#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
|
||||
SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0");
|
||||
#endif
|
||||
|
||||
(void)sdl_gl_context; // Unused in 'master' branch.
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
|
||||
{
|
||||
return ImGui_ImplSDL2_Init(window, nullptr, sdl_gl_context);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
|
||||
{
|
||||
#if !SDL_HAS_VULKAN
|
||||
IM_ASSERT(0 && "Unsupported");
|
||||
#endif
|
||||
return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window)
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
IM_ASSERT(0 && "Unsupported");
|
||||
#endif
|
||||
return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window)
|
||||
{
|
||||
return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
|
||||
{
|
||||
return ImGui_ImplSDL2_Init(window, renderer, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL2_InitForOther(SDL_Window* window)
|
||||
{
|
||||
return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_CloseGamepads();
|
||||
|
||||
void ImGui_ImplSDL2_Shutdown()
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
if (bd->ClipboardTextData)
|
||||
SDL_free(bd->ClipboardTextData);
|
||||
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
|
||||
SDL_FreeCursor(bd->MouseCursors[cursor_n]);
|
||||
ImGui_ImplSDL2_CloseGamepads();
|
||||
|
||||
io.BackendPlatformName = nullptr;
|
||||
io.BackendPlatformUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_UpdateMouseData()
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below)
|
||||
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
|
||||
// - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside.
|
||||
// - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture.
|
||||
if (bd->MouseCanUseCapture)
|
||||
{
|
||||
bool want_capture = false;
|
||||
for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++)
|
||||
if (ImGui::IsMouseDragging(button_n, 1.0f))
|
||||
want_capture = true;
|
||||
SDL_CaptureMouse(want_capture ? SDL_TRUE : SDL_FALSE);
|
||||
}
|
||||
|
||||
SDL_Window* focused_window = SDL_GetKeyboardFocus();
|
||||
const bool is_app_focused = (bd->Window == focused_window);
|
||||
#else
|
||||
const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only
|
||||
#endif
|
||||
if (is_app_focused)
|
||||
{
|
||||
// (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
|
||||
if (io.WantSetMousePos)
|
||||
SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y);
|
||||
|
||||
// (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured)
|
||||
const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0;
|
||||
if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode)
|
||||
{
|
||||
// Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
|
||||
int window_x, window_y, mouse_x_global, mouse_y_global;
|
||||
SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global);
|
||||
SDL_GetWindowPosition(bd->Window, &window_x, &window_y);
|
||||
io.AddMousePosEvent((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_UpdateMouseCursor()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
|
||||
return;
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
|
||||
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
|
||||
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
|
||||
{
|
||||
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
|
||||
SDL_ShowCursor(SDL_FALSE);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Show OS mouse cursor
|
||||
SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
|
||||
if (bd->MouseLastCursor != expected_cursor)
|
||||
{
|
||||
SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
|
||||
bd->MouseLastCursor = expected_cursor;
|
||||
}
|
||||
SDL_ShowCursor(SDL_TRUE);
|
||||
}
|
||||
}
|
||||
|
||||
// - On Windows the process needs to be marked DPI-aware!! SDL2 doesn't do it by default. You can call ::SetProcessDPIAware() or call ImGui_ImplWin32_EnableDpiAwareness() from Win32 backend.
|
||||
// - Apple platforms use FramebufferScale so we always return 1.0f.
|
||||
// - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle.
|
||||
float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window)
|
||||
{
|
||||
return ImGui_ImplSDL2_GetContentScaleForDisplay(SDL_GetWindowDisplayIndex(window));
|
||||
}
|
||||
|
||||
float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index)
|
||||
{
|
||||
#if SDL_HAS_PER_MONITOR_DPI
|
||||
#ifndef __APPLE__
|
||||
float dpi = 0.0f;
|
||||
if (SDL_GetDisplayDPI(display_index, &dpi, nullptr, nullptr) == 0)
|
||||
return dpi / 96.0f;
|
||||
#endif
|
||||
#endif
|
||||
IM_UNUSED(display_index);
|
||||
return 1.0f;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_CloseGamepads()
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
if (bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
|
||||
for (SDL_GameController* gamepad : bd->Gamepads)
|
||||
SDL_GameControllerClose(gamepad);
|
||||
bd->Gamepads.resize(0);
|
||||
}
|
||||
|
||||
void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array, int manual_gamepads_count)
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
ImGui_ImplSDL2_CloseGamepads();
|
||||
if (mode == ImGui_ImplSDL2_GamepadMode_Manual)
|
||||
{
|
||||
IM_ASSERT(manual_gamepads_array != nullptr || manual_gamepads_count <= 0);
|
||||
for (int n = 0; n < manual_gamepads_count; n++)
|
||||
bd->Gamepads.push_back(manual_gamepads_array[n]);
|
||||
}
|
||||
else
|
||||
{
|
||||
IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
|
||||
bd->WantUpdateGamepadsList = true;
|
||||
}
|
||||
bd->GamepadMode = mode;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_UpdateGamepadButton(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerButton button_no)
|
||||
{
|
||||
bool merged_value = false;
|
||||
for (SDL_GameController* gamepad : bd->Gamepads)
|
||||
merged_value |= SDL_GameControllerGetButton(gamepad, button_no) != 0;
|
||||
io.AddKeyEvent(key, merged_value);
|
||||
}
|
||||
|
||||
static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
|
||||
static void ImGui_ImplSDL2_UpdateGamepadAnalog(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerAxis axis_no, float v0, float v1)
|
||||
{
|
||||
float merged_value = 0.0f;
|
||||
for (SDL_GameController* gamepad : bd->Gamepads)
|
||||
{
|
||||
float vn = Saturate((float)(SDL_GameControllerGetAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
|
||||
if (merged_value < vn)
|
||||
merged_value = vn;
|
||||
}
|
||||
io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_UpdateGamepads()
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Update list of controller(s) to use
|
||||
if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
|
||||
{
|
||||
ImGui_ImplSDL2_CloseGamepads();
|
||||
int joystick_count = SDL_NumJoysticks();
|
||||
for (int n = 0; n < joystick_count; n++)
|
||||
if (SDL_IsGameController(n))
|
||||
if (SDL_GameController* gamepad = SDL_GameControllerOpen(n))
|
||||
{
|
||||
bd->Gamepads.push_back(gamepad);
|
||||
if (bd->GamepadMode == ImGui_ImplSDL2_GamepadMode_AutoFirst)
|
||||
break;
|
||||
}
|
||||
bd->WantUpdateGamepadsList = false;
|
||||
}
|
||||
|
||||
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
|
||||
if (bd->Gamepads.Size == 0)
|
||||
return;
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
|
||||
|
||||
// Update gamepad inputs
|
||||
const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value.
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK);
|
||||
ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(SDL_Window* window, SDL_Renderer* renderer, ImVec2* out_size, ImVec2* out_framebuffer_scale)
|
||||
{
|
||||
int w, h;
|
||||
int display_w, display_h;
|
||||
SDL_GetWindowSize(window, &w, &h);
|
||||
if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
|
||||
w = h = 0;
|
||||
if (renderer != nullptr)
|
||||
SDL_GetRendererOutputSize(renderer, &display_w, &display_h);
|
||||
#if SDL_HAS_VULKAN
|
||||
else if (SDL_GetWindowFlags(window) & SDL_WINDOW_VULKAN)
|
||||
SDL_Vulkan_GetDrawableSize(window, &display_w, &display_h);
|
||||
#endif
|
||||
else
|
||||
SDL_GL_GetDrawableSize(window, &display_w, &display_h);
|
||||
if (out_size != nullptr)
|
||||
*out_size = ImVec2((float)w, (float)h);
|
||||
if (out_framebuffer_scale != nullptr)
|
||||
*out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / w, (float)display_h / h) : ImVec2(1.0f, 1.0f);
|
||||
}
|
||||
|
||||
void ImGui_ImplSDL2_NewFrame()
|
||||
{
|
||||
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Setup main viewport size (every frame to accommodate for window resizing)
|
||||
ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(bd->Window, bd->Renderer, &io.DisplaySize, &io.DisplayFramebufferScale);
|
||||
|
||||
// Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
|
||||
// (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644)
|
||||
static Uint64 frequency = SDL_GetPerformanceFrequency();
|
||||
Uint64 current_time = SDL_GetPerformanceCounter();
|
||||
if (current_time <= bd->Time)
|
||||
current_time = bd->Time + 1;
|
||||
io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
|
||||
bd->Time = current_time;
|
||||
|
||||
if (bd->MouseLastLeaveFrame && bd->MouseLastLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
|
||||
{
|
||||
bd->MouseWindowID = 0;
|
||||
bd->MouseLastLeaveFrame = 0;
|
||||
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
|
||||
}
|
||||
|
||||
ImGui_ImplSDL2_UpdateMouseData();
|
||||
ImGui_ImplSDL2_UpdateMouseCursor();
|
||||
|
||||
// Update game controllers (if enabled and available)
|
||||
ImGui_ImplSDL2_UpdateGamepads();
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
@@ -1,50 +0,0 @@
|
||||
// dear imgui: Platform Backend for SDL2
|
||||
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
|
||||
// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Clipboard support.
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Gamepad support.
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#ifndef IMGUI_DISABLE
|
||||
|
||||
struct SDL_Window;
|
||||
struct SDL_Renderer;
|
||||
struct _SDL_GameController;
|
||||
typedef union SDL_Event SDL_Event;
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context);
|
||||
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window);
|
||||
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window);
|
||||
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window);
|
||||
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer);
|
||||
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOther(SDL_Window* window);
|
||||
IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame();
|
||||
IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event);
|
||||
|
||||
// DPI-related helpers (optional)
|
||||
IMGUI_IMPL_API float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window);
|
||||
IMGUI_IMPL_API float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index);
|
||||
|
||||
// Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
|
||||
// When using manual mode, caller is responsible for opening/closing gamepad.
|
||||
enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual };
|
||||
IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = nullptr, int manual_gamepads_count = -1);
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
830
source/thirdparty/imgui/backends/imgui_impl_sdl3.cpp
vendored
830
source/thirdparty/imgui/backends/imgui_impl_sdl3.cpp
vendored
@@ -1,830 +0,0 @@
|
||||
// dear imgui: Platform Backend for SDL3
|
||||
// This needs to be used along with a Renderer (e.g. SDL_GPU, DirectX11, OpenGL3, Vulkan..)
|
||||
// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Clipboard support.
|
||||
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
|
||||
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
|
||||
// [X] Platform: Gamepad support.
|
||||
// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// [X] Platform: IME support.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2025-06-27: IME: avoid calling SDL_StartTextInput() again if already active. (#8727)
|
||||
// 2025-04-22: IME: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible.
|
||||
// 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561)
|
||||
// 2025-03-30: Update for SDL3 api changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801)
|
||||
// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set.
|
||||
// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468)
|
||||
// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650)
|
||||
// 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode.
|
||||
// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support.
|
||||
// 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler.
|
||||
// 2025-01-20: Made ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode_Manual) accept an empty array.
|
||||
// 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten.
|
||||
// 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807)
|
||||
// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
|
||||
// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
|
||||
// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
|
||||
// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
|
||||
// 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*.
|
||||
// 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853)
|
||||
// 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807)
|
||||
// 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801)
|
||||
// 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794)
|
||||
// 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762).
|
||||
// 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea().
|
||||
// 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures.
|
||||
// 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents.
|
||||
// 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames.
|
||||
// 2024-05-15: Update for SDL3 api changes: SDLK_ renames.
|
||||
// 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME.
|
||||
// 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode().
|
||||
// 2023-11-13: Updated for recent SDL3 API changes.
|
||||
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
|
||||
// 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391)
|
||||
// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
|
||||
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
|
||||
// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
|
||||
// 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog.
|
||||
|
||||
#include "imgui.h"
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui_impl_sdl3.h"
|
||||
|
||||
// Clang warnings with -Weverything
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
|
||||
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
|
||||
#endif
|
||||
|
||||
// SDL
|
||||
#include <SDL3/SDL.h>
|
||||
#include <stdio.h> // for snprintf()
|
||||
#if defined(__APPLE__)
|
||||
#include <TargetConditionals.h>
|
||||
#endif
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
|
||||
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
|
||||
#else
|
||||
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
|
||||
#endif
|
||||
|
||||
// FIXME-LEGACY: remove when SDL 3.1.3 preview is released.
|
||||
#ifndef SDLK_APOSTROPHE
|
||||
#define SDLK_APOSTROPHE SDLK_QUOTE
|
||||
#endif
|
||||
#ifndef SDLK_GRAVE
|
||||
#define SDLK_GRAVE SDLK_BACKQUOTE
|
||||
#endif
|
||||
|
||||
// SDL Data
|
||||
struct ImGui_ImplSDL3_Data
|
||||
{
|
||||
SDL_Window* Window;
|
||||
SDL_WindowID WindowID;
|
||||
SDL_Renderer* Renderer;
|
||||
Uint64 Time;
|
||||
char* ClipboardTextData;
|
||||
char BackendPlatformName[48];
|
||||
|
||||
// IME handling
|
||||
SDL_Window* ImeWindow;
|
||||
|
||||
// Mouse handling
|
||||
Uint32 MouseWindowID;
|
||||
int MouseButtonsDown;
|
||||
SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
|
||||
SDL_Cursor* MouseLastCursor;
|
||||
int MousePendingLeaveFrame;
|
||||
bool MouseCanUseGlobalState;
|
||||
bool MouseCanUseCapture;
|
||||
|
||||
// Gamepad handling
|
||||
ImVector<SDL_Gamepad*> Gamepads;
|
||||
ImGui_ImplSDL3_GamepadMode GamepadMode;
|
||||
bool WantUpdateGamepadsList;
|
||||
|
||||
ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
|
||||
// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
|
||||
static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
|
||||
}
|
||||
|
||||
// Functions
|
||||
static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*)
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
if (bd->ClipboardTextData)
|
||||
SDL_free(bd->ClipboardTextData);
|
||||
bd->ClipboardTextData = SDL_GetClipboardText();
|
||||
return bd->ClipboardTextData;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text)
|
||||
{
|
||||
SDL_SetClipboardText(text);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle;
|
||||
SDL_Window* window = SDL_GetWindowFromID(window_id);
|
||||
if ((!(data->WantVisible || data->WantTextInput) || bd->ImeWindow != window) && bd->ImeWindow != nullptr)
|
||||
{
|
||||
SDL_StopTextInput(bd->ImeWindow);
|
||||
bd->ImeWindow = nullptr;
|
||||
}
|
||||
if (data->WantVisible)
|
||||
{
|
||||
SDL_Rect r;
|
||||
r.x = (int)data->InputPos.x;
|
||||
r.y = (int)data->InputPos.y;
|
||||
r.w = 1;
|
||||
r.h = (int)data->InputLineHeight;
|
||||
SDL_SetTextInputArea(window, &r, 0);
|
||||
bd->ImeWindow = window;
|
||||
}
|
||||
if (!SDL_TextInputActive(window) && (data->WantVisible || data->WantTextInput))
|
||||
SDL_StartTextInput(window);
|
||||
}
|
||||
|
||||
// Not static to allow third-party code to use that if they want to (but undocumented)
|
||||
ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
|
||||
ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
|
||||
{
|
||||
// Keypad doesn't have individual key values in SDL3
|
||||
switch (scancode)
|
||||
{
|
||||
case SDL_SCANCODE_KP_0: return ImGuiKey_Keypad0;
|
||||
case SDL_SCANCODE_KP_1: return ImGuiKey_Keypad1;
|
||||
case SDL_SCANCODE_KP_2: return ImGuiKey_Keypad2;
|
||||
case SDL_SCANCODE_KP_3: return ImGuiKey_Keypad3;
|
||||
case SDL_SCANCODE_KP_4: return ImGuiKey_Keypad4;
|
||||
case SDL_SCANCODE_KP_5: return ImGuiKey_Keypad5;
|
||||
case SDL_SCANCODE_KP_6: return ImGuiKey_Keypad6;
|
||||
case SDL_SCANCODE_KP_7: return ImGuiKey_Keypad7;
|
||||
case SDL_SCANCODE_KP_8: return ImGuiKey_Keypad8;
|
||||
case SDL_SCANCODE_KP_9: return ImGuiKey_Keypad9;
|
||||
case SDL_SCANCODE_KP_PERIOD: return ImGuiKey_KeypadDecimal;
|
||||
case SDL_SCANCODE_KP_DIVIDE: return ImGuiKey_KeypadDivide;
|
||||
case SDL_SCANCODE_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
|
||||
case SDL_SCANCODE_KP_MINUS: return ImGuiKey_KeypadSubtract;
|
||||
case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd;
|
||||
case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter;
|
||||
case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual;
|
||||
default: break;
|
||||
}
|
||||
switch (keycode)
|
||||
{
|
||||
case SDLK_TAB: return ImGuiKey_Tab;
|
||||
case SDLK_LEFT: return ImGuiKey_LeftArrow;
|
||||
case SDLK_RIGHT: return ImGuiKey_RightArrow;
|
||||
case SDLK_UP: return ImGuiKey_UpArrow;
|
||||
case SDLK_DOWN: return ImGuiKey_DownArrow;
|
||||
case SDLK_PAGEUP: return ImGuiKey_PageUp;
|
||||
case SDLK_PAGEDOWN: return ImGuiKey_PageDown;
|
||||
case SDLK_HOME: return ImGuiKey_Home;
|
||||
case SDLK_END: return ImGuiKey_End;
|
||||
case SDLK_INSERT: return ImGuiKey_Insert;
|
||||
case SDLK_DELETE: return ImGuiKey_Delete;
|
||||
case SDLK_BACKSPACE: return ImGuiKey_Backspace;
|
||||
case SDLK_SPACE: return ImGuiKey_Space;
|
||||
case SDLK_RETURN: return ImGuiKey_Enter;
|
||||
case SDLK_ESCAPE: return ImGuiKey_Escape;
|
||||
//case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe;
|
||||
case SDLK_COMMA: return ImGuiKey_Comma;
|
||||
//case SDLK_MINUS: return ImGuiKey_Minus;
|
||||
case SDLK_PERIOD: return ImGuiKey_Period;
|
||||
//case SDLK_SLASH: return ImGuiKey_Slash;
|
||||
case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
|
||||
//case SDLK_EQUALS: return ImGuiKey_Equal;
|
||||
//case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
|
||||
//case SDLK_BACKSLASH: return ImGuiKey_Backslash;
|
||||
//case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
|
||||
//case SDLK_GRAVE: return ImGuiKey_GraveAccent;
|
||||
case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
|
||||
case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
|
||||
case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
|
||||
case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen;
|
||||
case SDLK_PAUSE: return ImGuiKey_Pause;
|
||||
case SDLK_LCTRL: return ImGuiKey_LeftCtrl;
|
||||
case SDLK_LSHIFT: return ImGuiKey_LeftShift;
|
||||
case SDLK_LALT: return ImGuiKey_LeftAlt;
|
||||
case SDLK_LGUI: return ImGuiKey_LeftSuper;
|
||||
case SDLK_RCTRL: return ImGuiKey_RightCtrl;
|
||||
case SDLK_RSHIFT: return ImGuiKey_RightShift;
|
||||
case SDLK_RALT: return ImGuiKey_RightAlt;
|
||||
case SDLK_RGUI: return ImGuiKey_RightSuper;
|
||||
case SDLK_APPLICATION: return ImGuiKey_Menu;
|
||||
case SDLK_0: return ImGuiKey_0;
|
||||
case SDLK_1: return ImGuiKey_1;
|
||||
case SDLK_2: return ImGuiKey_2;
|
||||
case SDLK_3: return ImGuiKey_3;
|
||||
case SDLK_4: return ImGuiKey_4;
|
||||
case SDLK_5: return ImGuiKey_5;
|
||||
case SDLK_6: return ImGuiKey_6;
|
||||
case SDLK_7: return ImGuiKey_7;
|
||||
case SDLK_8: return ImGuiKey_8;
|
||||
case SDLK_9: return ImGuiKey_9;
|
||||
case SDLK_A: return ImGuiKey_A;
|
||||
case SDLK_B: return ImGuiKey_B;
|
||||
case SDLK_C: return ImGuiKey_C;
|
||||
case SDLK_D: return ImGuiKey_D;
|
||||
case SDLK_E: return ImGuiKey_E;
|
||||
case SDLK_F: return ImGuiKey_F;
|
||||
case SDLK_G: return ImGuiKey_G;
|
||||
case SDLK_H: return ImGuiKey_H;
|
||||
case SDLK_I: return ImGuiKey_I;
|
||||
case SDLK_J: return ImGuiKey_J;
|
||||
case SDLK_K: return ImGuiKey_K;
|
||||
case SDLK_L: return ImGuiKey_L;
|
||||
case SDLK_M: return ImGuiKey_M;
|
||||
case SDLK_N: return ImGuiKey_N;
|
||||
case SDLK_O: return ImGuiKey_O;
|
||||
case SDLK_P: return ImGuiKey_P;
|
||||
case SDLK_Q: return ImGuiKey_Q;
|
||||
case SDLK_R: return ImGuiKey_R;
|
||||
case SDLK_S: return ImGuiKey_S;
|
||||
case SDLK_T: return ImGuiKey_T;
|
||||
case SDLK_U: return ImGuiKey_U;
|
||||
case SDLK_V: return ImGuiKey_V;
|
||||
case SDLK_W: return ImGuiKey_W;
|
||||
case SDLK_X: return ImGuiKey_X;
|
||||
case SDLK_Y: return ImGuiKey_Y;
|
||||
case SDLK_Z: return ImGuiKey_Z;
|
||||
case SDLK_F1: return ImGuiKey_F1;
|
||||
case SDLK_F2: return ImGuiKey_F2;
|
||||
case SDLK_F3: return ImGuiKey_F3;
|
||||
case SDLK_F4: return ImGuiKey_F4;
|
||||
case SDLK_F5: return ImGuiKey_F5;
|
||||
case SDLK_F6: return ImGuiKey_F6;
|
||||
case SDLK_F7: return ImGuiKey_F7;
|
||||
case SDLK_F8: return ImGuiKey_F8;
|
||||
case SDLK_F9: return ImGuiKey_F9;
|
||||
case SDLK_F10: return ImGuiKey_F10;
|
||||
case SDLK_F11: return ImGuiKey_F11;
|
||||
case SDLK_F12: return ImGuiKey_F12;
|
||||
case SDLK_F13: return ImGuiKey_F13;
|
||||
case SDLK_F14: return ImGuiKey_F14;
|
||||
case SDLK_F15: return ImGuiKey_F15;
|
||||
case SDLK_F16: return ImGuiKey_F16;
|
||||
case SDLK_F17: return ImGuiKey_F17;
|
||||
case SDLK_F18: return ImGuiKey_F18;
|
||||
case SDLK_F19: return ImGuiKey_F19;
|
||||
case SDLK_F20: return ImGuiKey_F20;
|
||||
case SDLK_F21: return ImGuiKey_F21;
|
||||
case SDLK_F22: return ImGuiKey_F22;
|
||||
case SDLK_F23: return ImGuiKey_F23;
|
||||
case SDLK_F24: return ImGuiKey_F24;
|
||||
case SDLK_AC_BACK: return ImGuiKey_AppBack;
|
||||
case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
|
||||
default: break;
|
||||
}
|
||||
|
||||
// Fallback to scancode
|
||||
switch (scancode)
|
||||
{
|
||||
case SDL_SCANCODE_GRAVE: return ImGuiKey_GraveAccent;
|
||||
case SDL_SCANCODE_MINUS: return ImGuiKey_Minus;
|
||||
case SDL_SCANCODE_EQUALS: return ImGuiKey_Equal;
|
||||
case SDL_SCANCODE_LEFTBRACKET: return ImGuiKey_LeftBracket;
|
||||
case SDL_SCANCODE_RIGHTBRACKET: return ImGuiKey_RightBracket;
|
||||
case SDL_SCANCODE_NONUSBACKSLASH: return ImGuiKey_Oem102;
|
||||
case SDL_SCANCODE_BACKSLASH: return ImGuiKey_Backslash;
|
||||
case SDL_SCANCODE_SEMICOLON: return ImGuiKey_Semicolon;
|
||||
case SDL_SCANCODE_APOSTROPHE: return ImGuiKey_Apostrophe;
|
||||
case SDL_SCANCODE_COMMA: return ImGuiKey_Comma;
|
||||
case SDL_SCANCODE_PERIOD: return ImGuiKey_Period;
|
||||
case SDL_SCANCODE_SLASH: return ImGuiKey_Slash;
|
||||
default: break;
|
||||
}
|
||||
return ImGuiKey_None;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & SDL_KMOD_CTRL) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & SDL_KMOD_SHIFT) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & SDL_KMOD_ALT) != 0);
|
||||
io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0);
|
||||
}
|
||||
|
||||
|
||||
static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id)
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr;
|
||||
}
|
||||
|
||||
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
|
||||
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
|
||||
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
|
||||
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
|
||||
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
|
||||
bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
switch (event->type)
|
||||
{
|
||||
case SDL_EVENT_MOUSE_MOTION:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == nullptr)
|
||||
return false;
|
||||
ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
|
||||
io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
|
||||
io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_MOUSE_WHEEL:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == nullptr)
|
||||
return false;
|
||||
//IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
|
||||
float wheel_x = -event->wheel.x;
|
||||
float wheel_y = event->wheel.y;
|
||||
io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
|
||||
io.AddMouseWheelEvent(wheel_x, wheel_y);
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_MOUSE_BUTTON_DOWN:
|
||||
case SDL_EVENT_MOUSE_BUTTON_UP:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == nullptr)
|
||||
return false;
|
||||
int mouse_button = -1;
|
||||
if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
|
||||
if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }
|
||||
if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }
|
||||
if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }
|
||||
if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }
|
||||
if (mouse_button == -1)
|
||||
break;
|
||||
io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
|
||||
io.AddMouseButtonEvent(mouse_button, (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN));
|
||||
bd->MouseButtonsDown = (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_TEXT_INPUT:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == nullptr)
|
||||
return false;
|
||||
io.AddInputCharactersUTF8(event->text.text);
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_KEY_DOWN:
|
||||
case SDL_EVENT_KEY_UP:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == nullptr)
|
||||
return false;
|
||||
ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod);
|
||||
//IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%s : key=%d ('%s'), scancode=%d ('%s'), mod=%X\n",
|
||||
// (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP ", event->key.key, SDL_GetKeyName(event->key.key), event->key.scancode, SDL_GetScancodeName(event->key.scancode), event->key.mod);
|
||||
ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode);
|
||||
io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN));
|
||||
io.SetKeyEventNativeData(key, (int)event->key.key, (int)event->key.scancode, (int)event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_WINDOW_MOUSE_ENTER:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
|
||||
return false;
|
||||
bd->MouseWindowID = event->window.windowID;
|
||||
bd->MousePendingLeaveFrame = 0;
|
||||
return true;
|
||||
}
|
||||
// - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
|
||||
// causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why
|
||||
// we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.
|
||||
// FIXME: Unconfirmed whether this is still needed with SDL3.
|
||||
case SDL_EVENT_WINDOW_MOUSE_LEAVE:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
|
||||
return false;
|
||||
bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1;
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_WINDOW_FOCUS_GAINED:
|
||||
case SDL_EVENT_WINDOW_FOCUS_LOST:
|
||||
{
|
||||
if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
|
||||
return false;
|
||||
io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED);
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_GAMEPAD_ADDED:
|
||||
case SDL_EVENT_GAMEPAD_REMOVED:
|
||||
{
|
||||
bd->WantUpdateGamepadsList = true;
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window)
|
||||
{
|
||||
viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(window);
|
||||
viewport->PlatformHandleRaw = nullptr;
|
||||
#if defined(_WIN32) && !defined(__WINRT__)
|
||||
viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr);
|
||||
#elif defined(__APPLE__)
|
||||
viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr);
|
||||
#endif
|
||||
}
|
||||
|
||||
static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IMGUI_CHECKVERSION();
|
||||
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
|
||||
IM_UNUSED(sdl_gl_context); // Unused in this branch
|
||||
|
||||
const int ver_linked = SDL_GetVersion();
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)();
|
||||
snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl3 (%d.%d.%d; %d.%d.%d)",
|
||||
SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION, SDL_VERSIONNUM_MAJOR(ver_linked), SDL_VERSIONNUM_MINOR(ver_linked), SDL_VERSIONNUM_MICRO(ver_linked));
|
||||
io.BackendPlatformUserData = (void*)bd;
|
||||
io.BackendPlatformName = bd->BackendPlatformName;
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
|
||||
|
||||
bd->Window = window;
|
||||
bd->WindowID = SDL_GetWindowID(window);
|
||||
bd->Renderer = renderer;
|
||||
|
||||
// Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse()
|
||||
// ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
|
||||
bd->MouseCanUseGlobalState = false;
|
||||
bd->MouseCanUseCapture = false;
|
||||
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
|
||||
const char* sdl_backend = SDL_GetCurrentVideoDriver();
|
||||
const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
|
||||
for (const char* item : capture_and_global_state_whitelist)
|
||||
if (strncmp(sdl_backend, item, strlen(item)) == 0)
|
||||
bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true;
|
||||
#endif
|
||||
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText;
|
||||
platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText;
|
||||
platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData;
|
||||
platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; };
|
||||
|
||||
// Gamepad handling
|
||||
bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst;
|
||||
bd->WantUpdateGamepadsList = true;
|
||||
|
||||
// Load mouse cursors
|
||||
bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT);
|
||||
bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE);
|
||||
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE);
|
||||
bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER);
|
||||
bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT);
|
||||
bd->MouseCursors[ImGuiMouseCursor_Progress] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_PROGRESS);
|
||||
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED);
|
||||
|
||||
// Set platform dependent data in viewport
|
||||
// Our mouse update function expect PlatformHandle to be filled for the main viewport
|
||||
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
|
||||
ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window);
|
||||
|
||||
// From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
|
||||
// Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
|
||||
// (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application.
|
||||
// It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click:
|
||||
// you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED)
|
||||
#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH
|
||||
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
|
||||
#endif
|
||||
|
||||
// From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710)
|
||||
#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
|
||||
SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0");
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
|
||||
{
|
||||
IM_UNUSED(sdl_gl_context); // Viewport branch will need this.
|
||||
return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window)
|
||||
{
|
||||
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window)
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
IM_ASSERT(0 && "Unsupported");
|
||||
#endif
|
||||
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window)
|
||||
{
|
||||
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
|
||||
{
|
||||
return ImGui_ImplSDL3_Init(window, renderer, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL3_InitForSDLGPU(SDL_Window* window)
|
||||
{
|
||||
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool ImGui_ImplSDL3_InitForOther(SDL_Window* window)
|
||||
{
|
||||
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_CloseGamepads();
|
||||
|
||||
void ImGui_ImplSDL3_Shutdown()
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
if (bd->ClipboardTextData)
|
||||
SDL_free(bd->ClipboardTextData);
|
||||
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
|
||||
SDL_DestroyCursor(bd->MouseCursors[cursor_n]);
|
||||
ImGui_ImplSDL3_CloseGamepads();
|
||||
|
||||
io.BackendPlatformName = nullptr;
|
||||
io.BackendPlatformUserData = nullptr;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad);
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_UpdateMouseData()
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below)
|
||||
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
|
||||
// - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside.
|
||||
// - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture.
|
||||
if (bd->MouseCanUseCapture)
|
||||
{
|
||||
bool want_capture = false;
|
||||
for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++)
|
||||
if (ImGui::IsMouseDragging(button_n, 1.0f))
|
||||
want_capture = true;
|
||||
SDL_CaptureMouse(want_capture);
|
||||
}
|
||||
|
||||
SDL_Window* focused_window = SDL_GetKeyboardFocus();
|
||||
const bool is_app_focused = (bd->Window == focused_window);
|
||||
#else
|
||||
SDL_Window* focused_window = bd->Window;
|
||||
const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only
|
||||
#endif
|
||||
if (is_app_focused)
|
||||
{
|
||||
// (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
|
||||
if (io.WantSetMousePos)
|
||||
SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y);
|
||||
|
||||
// (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured)
|
||||
const bool is_relative_mouse_mode = SDL_GetWindowRelativeMouseMode(bd->Window);
|
||||
if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode)
|
||||
{
|
||||
// Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
|
||||
float mouse_x_global, mouse_y_global;
|
||||
int window_x, window_y;
|
||||
SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global);
|
||||
SDL_GetWindowPosition(focused_window, &window_x, &window_y);
|
||||
io.AddMousePosEvent(mouse_x_global - window_x, mouse_y_global - window_y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_UpdateMouseCursor()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
|
||||
return;
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
|
||||
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
|
||||
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
|
||||
{
|
||||
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
|
||||
SDL_HideCursor();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Show OS mouse cursor
|
||||
SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
|
||||
if (bd->MouseLastCursor != expected_cursor)
|
||||
{
|
||||
SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
|
||||
bd->MouseLastCursor = expected_cursor;
|
||||
}
|
||||
SDL_ShowCursor();
|
||||
}
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_CloseGamepads()
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
|
||||
for (SDL_Gamepad* gamepad : bd->Gamepads)
|
||||
SDL_CloseGamepad(gamepad);
|
||||
bd->Gamepads.resize(0);
|
||||
}
|
||||
|
||||
void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count)
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
ImGui_ImplSDL3_CloseGamepads();
|
||||
if (mode == ImGui_ImplSDL3_GamepadMode_Manual)
|
||||
{
|
||||
IM_ASSERT(manual_gamepads_array != nullptr || manual_gamepads_count <= 0);
|
||||
for (int n = 0; n < manual_gamepads_count; n++)
|
||||
bd->Gamepads.push_back(manual_gamepads_array[n]);
|
||||
}
|
||||
else
|
||||
{
|
||||
IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
|
||||
bd->WantUpdateGamepadsList = true;
|
||||
}
|
||||
bd->GamepadMode = mode;
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no)
|
||||
{
|
||||
bool merged_value = false;
|
||||
for (SDL_Gamepad* gamepad : bd->Gamepads)
|
||||
merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0;
|
||||
io.AddKeyEvent(key, merged_value);
|
||||
}
|
||||
|
||||
static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
|
||||
static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1)
|
||||
{
|
||||
float merged_value = 0.0f;
|
||||
for (SDL_Gamepad* gamepad : bd->Gamepads)
|
||||
{
|
||||
float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
|
||||
if (merged_value < vn)
|
||||
merged_value = vn;
|
||||
}
|
||||
io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_UpdateGamepads()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
|
||||
// Update list of gamepads to use
|
||||
if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
|
||||
{
|
||||
ImGui_ImplSDL3_CloseGamepads();
|
||||
int sdl_gamepads_count = 0;
|
||||
SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count);
|
||||
for (int n = 0; n < sdl_gamepads_count; n++)
|
||||
if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n]))
|
||||
{
|
||||
bd->Gamepads.push_back(gamepad);
|
||||
if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst)
|
||||
break;
|
||||
}
|
||||
bd->WantUpdateGamepadsList = false;
|
||||
SDL_free(sdl_gamepads);
|
||||
}
|
||||
|
||||
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
|
||||
if (bd->Gamepads.Size == 0)
|
||||
return;
|
||||
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
|
||||
|
||||
// Update gamepad inputs
|
||||
const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value.
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK);
|
||||
ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768);
|
||||
ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767);
|
||||
}
|
||||
|
||||
static void ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(SDL_Window* window, ImVec2* out_size, ImVec2* out_framebuffer_scale)
|
||||
{
|
||||
int w, h;
|
||||
int display_w, display_h;
|
||||
SDL_GetWindowSize(window, &w, &h);
|
||||
if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
|
||||
w = h = 0;
|
||||
SDL_GetWindowSizeInPixels(window, &display_w, &display_h);
|
||||
if (out_size != nullptr)
|
||||
*out_size = ImVec2((float)w, (float)h);
|
||||
if (out_framebuffer_scale != nullptr)
|
||||
*out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / w, (float)display_h / h) : ImVec2(1.0f, 1.0f);
|
||||
}
|
||||
|
||||
void ImGui_ImplSDL3_NewFrame()
|
||||
{
|
||||
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
|
||||
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Setup main viewport size (every frame to accommodate for window resizing)
|
||||
ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(bd->Window, &io.DisplaySize, &io.DisplayFramebufferScale);
|
||||
|
||||
// Setup time step (we could also use SDL_GetTicksNS() available since SDL3)
|
||||
// (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644)
|
||||
static Uint64 frequency = SDL_GetPerformanceFrequency();
|
||||
Uint64 current_time = SDL_GetPerformanceCounter();
|
||||
if (current_time <= bd->Time)
|
||||
current_time = bd->Time + 1;
|
||||
io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
|
||||
bd->Time = current_time;
|
||||
|
||||
if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
|
||||
{
|
||||
bd->MouseWindowID = 0;
|
||||
bd->MousePendingLeaveFrame = 0;
|
||||
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
|
||||
}
|
||||
|
||||
ImGui_ImplSDL3_UpdateMouseData();
|
||||
ImGui_ImplSDL3_UpdateMouseCursor();
|
||||
|
||||
// Update game controllers (if enabled and available)
|
||||
ImGui_ImplSDL3_UpdateGamepads();
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user