imroved circle shaders

This commit is contained in:
John Alanbrook 2023-05-25 01:45:50 +00:00
parent c16a0332a5
commit 9045f435a0
51 changed files with 828 additions and 9429 deletions

View file

@ -4,28 +4,28 @@ MAKEFLAGS = --jobs=$(PROCS)
UNAME != uname UNAME != uname
# Options # Options
# DBG=0,1 --- build with debugging symbols and logging # DBG --- build with debugging symbols and logging
# ED=0,1 --- build with or without editor # ED --- build with or without editor
# OPT --- Optimize
ED ?= 1 QFLAGS :=
DBG ?= 1
ifeq ($(DBG), 1) ifdef DBG
LVL = -O2 -g QFLAGS += -O0 -g -DDBG
INFO = dbg INFO = dbg
ifeq ($(CC), tcc)
LVL +=
endif
else else
LVL = -O2 -DNDEBUG -flto QFLAGS += -O2
INFO = rel INFO = rel
CC = gcc
endif endif
# QuickJS options ifdef OPT
QFLAGS += -flto
endif
QFLAGS = $(LVL) -DDBG=$(DBG) -DED=$(ED) ifdef ED
QFLAGS += -DED
endif
PTYPE != uname -m PTYPE != uname -m
@ -83,7 +83,7 @@ ifeq ($(OS), WIN32)
EXT = .exe EXT = .exe
else else
LINKER_FLAGS = $(QFLAGS) -L/usr/local/lib -rdynamic LINKER_FLAGS = $(QFLAGS) -L/usr/local/lib -rdynamic
ELIBS = engine pthread yughc glfw3 tcc quickjs c m dl GL ELIBS = engine pthread yughc glfw3 quickjs c m dl GL
CLIBS = CLIBS =
endif endif

View file

@ -116,6 +116,22 @@ assets for it.
- hit.velocity: Velocity of impact - hit.velocity: Velocity of impact
- hit.normal: Normal of impact - hit.normal: Normal of impact
.Colliders
Colliders visually look different based on their status. Objects can
be in one of three states
- Dynamic: respond to physics
- Kinematic: modeled with infinite momentum. An "unstoppable force"
controlled by a user.
- Static: modeled with infinite mass. An "immovable object" that
shouldn't move.
Objects can then have colliders on them, each collider being a sensor,
or solid. Sensors respond to collision signals, while solid ones also
do not let objects through.
.Input .Input
Input works by adding functions to an object, and then "controlling" Input works by adding functions to an object, and then "controlling"
them. The format for a function is "input_[key]_[action]". [Action] them. The format for a function is "input_[key]_[action]". [Action]

View file

@ -81,3 +81,13 @@ collide(hit)
hit - Object ID of colliding object hit - Object ID of colliding object
sensor - True if the colliding object is a sensor sensor - True if the colliding object is a sensor
velocity - A vector of the velocity of the collision velocity - A vector of the velocity of the collision
.Draw functions
draw()
Called during lower rendering
gui()
Called for screen space over the top rendering
debug()
Called during a debug phase; Will not be called when debug draw is off

View file

@ -2,7 +2,6 @@
#include "debug.h" #include "debug.h"
#include "gameobject.h" #include "gameobject.h"
#include "mathc.h"
#include "nuke.h" #include "nuke.h"
#include <string.h> #include <string.h>
@ -22,42 +21,17 @@
#include "log.h" #include "log.h"
cpSpace *space = NULL; cpSpace *space = NULL;
float phys2d_gravity = -50.f;
struct rgba color_white = {255,255,255,255}; struct rgba color_white = {255,255,255,255};
struct rgba color_black = {0,0,0,255}; struct rgba color_black = {0,0,0,255};
struct rgba dbg_color = { struct rgba disabled_color = {148,148,148,255};
.r = 0.836*255, struct rgba sleep_color = {255,140,228,255};
.g = 255, struct rgba dynamic_color = {255,70,46,255};
.b = 0.45*255, struct rgba kinematic_color = {255, 194, 64, 255};
.a = 255 struct rgba static_color = {73,209,80,255};
};
struct rgba trigger_color = { static const unsigned char col_alpha = 40;
.r = 0.278*255,
.g = 0.953*255,
.b = 255,
.a = 255
};
struct rgba disabled_color = {
.r = 0.58*255,
.g = 0.58*255,
.b = 0.58*255,
.a = 255
};
struct rgba dynamic_color = {
.r = 255,
.g = 70,
.b = 46,
.a = 255
};
struct rgba kinematic_color = {255, 206, 71, 255};
struct rgba static_color = {
.r = 0.22*255,
.g = 0.271*255,
.b = 255,
.a = 255
};
unsigned int category_masks[32]; unsigned int category_masks[32];
@ -167,9 +141,12 @@ int cpshape_enabled(cpShape *c) {
return 1; return 1;
} }
struct rgba shape_outline_color(cpShape *shape) { struct rgba shape_color(cpShape *shape) {
switch (cpBodyGetType(cpShapeGetBody(shape))) { switch (cpBodyGetType(cpShapeGetBody(shape))) {
case CP_BODY_TYPE_DYNAMIC: case CP_BODY_TYPE_DYNAMIC:
// cpBodySleep(cpShapeGetBody(shape));
if (cpBodyIsSleeping(cpShapeGetBody(shape)))
return sleep_color;
return dynamic_color; return dynamic_color;
case CP_BODY_TYPE_KINEMATIC: case CP_BODY_TYPE_KINEMATIC:
@ -182,23 +159,10 @@ struct rgba shape_outline_color(cpShape *shape) {
return static_color; return static_color;
} }
struct rgba shape_color(cpShape *shape) { void phys2d_init()
if (!cpshape_enabled(shape)) return disabled_color; {
if (cpShapeGetSensor(shape)) return trigger_color;
return dbg_color;
}
struct rgba shape_color_s(cpShape *shape) {
return shape_color(shape);
}
void phys2d_init() {
space = cpSpaceNew(); space = cpSpaceNew();
cpVect grav = {0, phys2d_gravity}; cpSpaceSetSleepTimeThreshold(space, 1);
phys2d_set_gravity(grav);
cpSpaceSetGravity(space, cpv(0, phys2d_gravity));
} }
void phys2d_set_gravity(cpVect v) { void phys2d_set_gravity(cpVect v) {
@ -295,7 +259,11 @@ cpVect bodytransformpoint(cpBody *body, cpVect offset) {
void phys2d_dbgdrawcpcirc(cpCircleShape *c) { void phys2d_dbgdrawcpcirc(cpCircleShape *c) {
cpVect pos = bodytransformpoint(cpShapeGetBody(c), cpCircleShapeGetOffset(c)); cpVect pos = bodytransformpoint(cpShapeGetBody(c), cpCircleShapeGetOffset(c));
float radius = cpCircleShapeGetRadius(c); float radius = cpCircleShapeGetRadius(c);
draw_circle(pos.x, pos.y, radius, 2, shape_color(c), 1); struct rgba color = shape_color(c);
float seglen = cpShapeGetSensor(c) ? 5 : -1;
draw_circle(pos.x, pos.y, radius, 1, color, seglen);
color.a = col_alpha;
draw_circle(pos.x,pos.y,radius,radius,color,-1);
} }
void phys2d_dbgdrawcircle(struct phys2d_circle *circle) { void phys2d_dbgdrawcircle(struct phys2d_circle *circle) {
@ -370,7 +338,7 @@ void phys2d_dbgdrawbox(struct phys2d_box *box) {
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
points[i] = bodytransformpoint(cpShapeGetBody(box->shape.shape), cpPolyShapeGetVert(box->shape.shape, i)); points[i] = bodytransformpoint(cpShapeGetBody(box->shape.shape), cpPolyShapeGetVert(box->shape.shape, i));
draw_poly(points, n, shape_color(box->shape.shape)); draw_poly(points, n, shape_color(box->shape.shape), shape_color(box->shape.shape), 0);
} }
/************** POLYGON ************/ /************** POLYGON ************/
@ -390,9 +358,9 @@ struct phys2d_poly *Make2DPoly(int go) {
float phys2d_poly_moi(struct phys2d_poly *poly, float m) { float phys2d_poly_moi(struct phys2d_poly *poly, float m) {
float moi = cpMomentForPoly(m, arrlen(poly->points), poly->points, cpvzero, poly->radius); float moi = cpMomentForPoly(m, arrlen(poly->points), poly->points, cpvzero, poly->radius);
if (moi <= 0) { if (isnan(moi)) {
YughError("Polygon MOI is negative. Returning one;"); // YughError("Polygon MOI returned an error. Returning 0.");
return 1; return 0;
} }
return moi; return moi;
@ -426,6 +394,8 @@ void phys2d_applypoly(struct phys2d_poly *poly) {
} }
void phys2d_dbgdrawpoly(struct phys2d_poly *poly) { void phys2d_dbgdrawpoly(struct phys2d_poly *poly) {
struct rgba color = shape_color(poly->shape.shape); struct rgba color = shape_color(poly->shape.shape);
struct rgba line_color = color;
color.a = col_alpha;
if (arrlen(poly->points) >= 3) { if (arrlen(poly->points) >= 3) {
int n = cpPolyShapeGetCount(poly->shape.shape); int n = cpPolyShapeGetCount(poly->shape.shape);
@ -434,7 +404,7 @@ void phys2d_dbgdrawpoly(struct phys2d_poly *poly) {
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
points[i] = bodytransformpoint(cpShapeGetBody(poly->shape.shape), cpPolyShapeGetVert(poly->shape.shape, i)); points[i] = bodytransformpoint(cpShapeGetBody(poly->shape.shape), cpPolyShapeGetVert(poly->shape.shape, i));
draw_poly(points, n, color); draw_poly(points, n, color, line_color, 0);
} }
} }
/****************** EDGE 2D**************/ /****************** EDGE 2D**************/
@ -451,6 +421,7 @@ struct phys2d_edge *Make2DEdge(int go) {
new->shape.debugdraw = phys2d_dbgdrawedge; new->shape.debugdraw = phys2d_dbgdrawedge;
new->shape.moi = phys2d_edge_moi; new->shape.moi = phys2d_edge_moi;
new->shape.shape = NULL; new->shape.shape = NULL;
new->draws = 0;
phys2d_applyedge(new); phys2d_applyedge(new);
return new; return new;
@ -558,7 +529,11 @@ void phys2d_dbgdrawedge(struct phys2d_edge *edge) {
drawpoints[i] = bodytransformpoint(cpShapeGetBody(edge->shapes[0]), drawpoints[i]); drawpoints[i] = bodytransformpoint(cpShapeGetBody(edge->shapes[0]), drawpoints[i]);
} }
draw_edge(drawpoints, arrlen(edge->points), shape_color_s(edge->shapes[0]), edge->thickness * 2, 0,0); float seglen = cpShapeGetSensor(edge->shapes[0]) ? 10 : 1;
struct rgba color = shape_color(edge->shapes[0]);
struct rgba line_color = color;
color.a = col_alpha;
draw_edge(drawpoints, arrlen(edge->points), color, edge->thickness * 2, 0,0, line_color, seglen);
draw_points(drawpoints, arrlen(edge->points), 2, kinematic_color); draw_points(drawpoints, arrlen(edge->points), 2, kinematic_color);
} }
@ -608,6 +583,8 @@ void duk_call_phys_cb(cpVect norm, struct callee c, int hit, cpArbiter *arb) {
JS_SetPropertyStr(js, obj, "hit", JS_NewInt32(js, hit)); JS_SetPropertyStr(js, obj, "hit", JS_NewInt32(js, hit));
JS_SetPropertyStr(js, obj, "sensor", JS_NewBool(js, cpShapeGetSensor(shape2))); JS_SetPropertyStr(js, obj, "sensor", JS_NewBool(js, cpShapeGetSensor(shape2)));
JS_SetPropertyStr(js, obj, "velocity", vec2js(cpArbiterGetSurfaceVelocity(arb))); JS_SetPropertyStr(js, obj, "velocity", vec2js(cpArbiterGetSurfaceVelocity(arb)));
JS_SetPropertyStr(js, obj, "pos", vec2js(cpArbiterGetPointA(arb, 0)));
JS_SetPropertyStr(js, obj, "id", JS_NewInt32(js,hit));
script_callee(c, 1, &obj); script_callee(c, 1, &obj);
} }

View file

@ -3,6 +3,7 @@
#include "script.h" #include "script.h"
#include <chipmunk/chipmunk.h> #include <chipmunk/chipmunk.h>
#include "render.h"
struct gameobject; struct gameobject;
@ -10,23 +11,15 @@ extern float phys2d_gravity;
extern int physOn; extern int physOn;
extern cpSpace *space; extern cpSpace *space;
struct rgba {
unsigned char r;
unsigned char g;
unsigned char b;
unsigned char a;
};
extern struct rgba color_white; extern struct rgba color_white;
extern struct rgba color_black; extern struct rgba color_black;
extern struct rgba dbg_color;
extern struct rgba trigger_color;
extern struct rgba disabled_color; extern struct rgba disabled_color;
extern struct rgba dynamic_color; extern struct rgba dynamic_color;
extern struct rgba kinematic_color; extern struct rgba kinematic_color;
extern struct rgba static_color; extern struct rgba static_color;
extern struct rgba sleep_color;
struct phys2d_shape { struct phys2d_shape {

View file

@ -7,19 +7,19 @@
struct follow { struct follow {
float distance; float distance;
mfloat_t target_rot[4]; HMM_Quat target_rot;
}; };
mfloat_t *follow_calccenter(); HMM_Vec3follow_calccenter();
mfloat_t *follow_postoffset(); HMM_Vec3follow_postoffset();
mfloat_t *extentsoffset(); HMM_Vec3extentsoffset();
mfloat_t *framebasedveclerp(); HMM_Vec3framebasedveclerp();
int lerpparam(float offset, float anchorwidth, float floatwidth); int lerpparam(float offset, float anchorwidth, float floatwidth);
mfloat_t *vec3lerp(mfloat_t from[3], mfloat_t to[3], mfloat_t a[3]); HMM_Vec3vec3lerp(HMM_Vec3 from, HMM_Vec3 to, HMM_Vec3 a);
void follow_calctargets(); void follow_calctargets();
mfloat_t *follow_removelockedrot(); HMM_Vec3follow_removelockedrot();
void follow_targetoffset(struct follow *follow); void follow_targetoffset(struct follow *follow);
int float_epsilon(mfloat_t a, mfloat_t b, mfloat_t e); int float_epsilon(float a, float b, float e);
/* /*

View file

@ -1,7 +1,6 @@
#ifndef MESH_H #ifndef MESH_H
#define MESH_H #define MESH_H
#include "mathc.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
#include <stdint.h> #include <stdint.h>

View file

@ -22,8 +22,6 @@
#include "texture.h" #include "texture.h"
#include "mathc.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
static struct { static struct {
@ -40,9 +38,7 @@ static sg_pipeline model_pipe;
void model_init() { void model_init() {
YughWarn("Creating model"); YughWarn("Creating model");
model_shader = sg_make_shader(&(sg_shader_desc){ model_shader = sg_compile_shader("shaders/diffuse_v.glsl", "shaders/diffuse_f.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/diffuse_v.glsl"),
.fs.source = slurp_text("shaders/diffuse_f.glsl"),
.vs.uniform_blocks[0] = { .vs.uniform_blocks[0] = {
.size = sizeof(float) * 16 * 4, .size = sizeof(float) * 16 * 4,
.uniforms = { .uniforms = {

File diff suppressed because it is too large Load diff

View file

@ -8,122 +8,15 @@ const float CAMERA_MAXSPEED = 300.f;
const float CAMERA_ROTATESPEED = 6.f; const float CAMERA_ROTATESPEED = 6.f;
void cam_goto_object(struct mCamera *cam, struct mTransform *transform) { void cam_goto_object(struct mCamera *cam, struct mTransform *transform) {
mfloat_t fwd[3] = {0.f}; cam->transform.pos = HMM_SubV3(transform->pos, HMM_MulV3F(trans_forward(transform), 10.0));
vec3_subtract(cam->transform.position, transform->position,
vec3_multiply_f(fwd, trans_forward(fwd, transform),
10.f));
} }
void cam_inverse_goto(struct mCamera *cam, struct mTransform *transform) { void cam_inverse_goto(struct mCamera *cam, struct mTransform *transform) {
mfloat_t fwd[3] = {0.f}; transform->pos = HMM_AddV3(cam->transform.pos, HMM_MulV3F(trans_forward(&cam->transform), 10.0));
vec3_add(transform->position, cam->transform.position,
vec3_multiply_f(fwd, trans_forward(fwd, &cam->transform),
10.f));
} }
mfloat_t *getviewmatrix(mfloat_t view[16], HMM_Mat4 getviewmatrix(const struct mCamera *const camera)
const struct mCamera *const camera) {
mfloat_t fwd[3] = {0.f};
mfloat_t look[3] = {0.f};
vec3_rotate_quat(fwd, FORWARD, camera->transform.rotation);
vec3_add(look, camera->transform.position, fwd);
mat4_look_at(view, camera->transform.position, look, UP);
return view;
/*return mat4_look_at(view, ncam.transform.position,
vec3_add(look, ncam.transform.position,
trans_forward(fwd, &ncam.transform)),
UP); */
}
void camera_2d_update(struct mCamera *camera, float deltaT) {
static mfloat_t frame[3];
vec3_zero(frame);
if (action_down(GLFW_KEY_W))
vec3_add(frame, frame, UP);
if (action_down(GLFW_KEY_S))
vec3_add(frame, frame, DOWN);
if (action_down(GLFW_KEY_A))
vec3_add(frame, frame, LEFT);
if (action_down(GLFW_KEY_D))
vec3_add(frame, frame, RIGHT);
float speedMult = action_down(GLFW_KEY_LEFT_SHIFT) ? 2.f : 1.f;
if (!vec3_is_zero(frame)) {
vec3_normalize(frame, frame);
vec3_add(camera->transform.position, camera->transform.position,
vec3_multiply_f(frame, frame,
camera->speed * speedMult * deltaT));
}
}
/*
void camera_update(struct mCamera * camera, float mouseX, float mouseY,
const uint8_t * keystate, int32_t mouseWheelY,
float deltaTime)
{ {
// if (SDL_GetRelativeMouseMode()) vec3_zero(camera->frame_move); HMM_Vec3 lookvec = HMM_AddV3(camera->transform.pos, trans_forward(&camera->transform.rotation));
return HMM_LookAt_RH(camera->transform.pos, lookvec, vY);
static mfloat_t holdvec[VEC3_SIZE];
vec3_zero(camera->frame_move);
if (currentKeystates[SDL_SCANCODE_W])
vec3_add(camera->frame_move, camera->frame_move,
trans_forward(holdvec, &camera->transform));
if (currentKeystates[SDL_SCANCODE_S])
vec3_subtract(camera->frame_move, camera->frame_move,
trans_forward(holdvec, &camera->transform));
if (currentKeystates[SDL_SCANCODE_A])
vec3_subtract(camera->frame_move, camera->frame_move,
trans_right(holdvec, &camera->transform));
if (currentKeystates[SDL_SCANCODE_D])
vec3_add(camera->frame_move, camera->frame_move,
trans_right(holdvec, &camera->transform));
if (currentKeystates[SDL_SCANCODE_E])
vec3_add(camera->frame_move, camera->frame_move,
trans_up(holdvec, &camera->transform));
if (currentKeystates[SDL_SCANCODE_Q])
vec3_subtract(camera->frame_move, camera->frame_move,
trans_up(holdvec, &camera->transform));
camera->speedMult = currentKeystates[SDL_SCANCODE_LSHIFT] ? 2.f : 1.f;
if (!vec3_is_zero(camera->frame_move)) {
vec3_normalize(camera->frame_move, camera->frame_move);
vec3_add(camera->transform.position, camera->transform.position,
vec3_multiply_f(camera->frame_move, camera->frame_move,
camera->speed * camera->speedMult *
deltaTime));
} }
// Adjust speed based on mouse wheel
camera->speed =
clampf(camera->speed + mouseWheelY, CAMERA_MINSPEED,
CAMERA_MAXSPEED);
// TODO: Handle this as additive quaternions
camera->yaw -= mouseX * CAMERA_ROTATESPEED * deltaTime;
camera->pitch -= mouseY * CAMERA_ROTATESPEED * deltaTime;
if (camera->pitch > 89.f)
camera->pitch = 89.f;
if (camera->pitch < -89.f)
camera->pitch = -89.f;
mfloat_t qyaw[4] = {0.f};
mfloat_t qpitch[4] = {0.f};
quat_from_axis_angle(qyaw, UP, camera->yaw);
quat_from_axis_angle(qpitch, RIGHT, camera->pitch);
quat_multiply(camera->transform.rotation, qyaw, qpitch);
}
*/

View file

@ -11,12 +11,12 @@ struct mCamera {
struct mTransform transform; struct mTransform transform;
float speed; float speed;
float speedMult; float speedMult;
mfloat_t frame_move[VEC3_SIZE]; HMM_Vec3 frame_move;
}; };
void camera_2d_update(struct mCamera *camera, float deltaT); void camera_2d_update(struct mCamera *camera, float deltaT);
mfloat_t *getviewmatrix(mfloat_t view[MAT4_SIZE], const struct mCamera *const camera); HMM_Mat4 getviewmatrix(const struct mCamera *const camera);
void cam_goto_object(struct mCamera *cam, struct mTransform *transform); void cam_goto_object(struct mCamera *cam, struct mTransform *transform);
void cam_inverse_goto(struct mCamera *cam, struct mTransform *transform); void cam_inverse_goto(struct mCamera *cam, struct mTransform *transform);

View file

@ -13,6 +13,8 @@
#include "texture.h" #include "texture.h"
#include <stdbool.h> #include <stdbool.h>
#include <stdlib.h> #include <stdlib.h>
#include "font.h"
#include "openglrender.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
@ -104,9 +106,7 @@ void ds_openvideo(struct datastream *ds, const char *video, const char *adriver)
} }
struct datastream *MakeDatastream() { struct datastream *MakeDatastream() {
vid_shader = sg_make_shader(&(sg_shader_desc){ vid_shader = sg_compile_shader("shaders/videovert.glsl", "shaders/videofrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/videovert.glsl"),
.fs.source = slurp_text("shaders/videofrag.glsl"),
.fs.images[0] = { .fs.images[0] = {
.name = "video", .name = "video",
.image_type = SG_IMAGETYPE_2D, .image_type = SG_IMAGETYPE_2D,

View file

@ -2,10 +2,7 @@
#define DEBUG_GUI_H #define DEBUG_GUI_H
#define static_assert(pred) switch(0){case 0:case pred:;} #define static_assert(pred) switch(0){case 0:case pred:;}
extern unsigned long long triCount; extern unsigned long long triCount;
void resetTriangles(); void resetTriangles();
#endif #endif

View file

@ -3,6 +3,8 @@
#include "openglrender.h" #include "openglrender.h"
#include "render.h" #include "render.h"
#include "yugine.h"
#include "shader.h" #include "shader.h"
#include "log.h" #include "log.h"
#include <assert.h> #include <assert.h>
@ -17,6 +19,8 @@
#include "font.h" #include "font.h"
#define v_amt 1000
static sg_shader point_shader; static sg_shader point_shader;
static sg_pipeline point_pipe; static sg_pipeline point_pipe;
static sg_bindings point_bind; static sg_bindings point_bind;
@ -26,7 +30,7 @@ struct point_vertex {
float radius; float radius;
}; };
static int point_c = 0; static int point_c = 0;
static struct point_vertex point_b[1000]; static struct point_vertex point_b[v_amt];
static sg_shader line_shader; static sg_shader line_shader;
static sg_pipeline line_pipe; static sg_pipeline line_pipe;
@ -39,8 +43,8 @@ struct line_vert {
}; };
static int line_c = 0; static int line_c = 0;
static int line_v = 0; static int line_v = 0;
static struct line_vert line_b[1000]; static struct line_vert line_b[v_amt];
static uint16_t line_bi[1000]; static uint16_t line_bi[v_amt];
static sg_pipeline grid_pipe; static sg_pipeline grid_pipe;
static sg_bindings grid_bind; static sg_bindings grid_bind;
@ -53,24 +57,26 @@ static sg_shader poly_shader;
static int poly_c = 0; static int poly_c = 0;
static int poly_v = 0; static int poly_v = 0;
struct poly_vertex { struct poly_vertex {
float pos[2]; cpVect pos;
float uv[2]; float uv[2];
struct rgba color; struct rgba color;
}; };
static struct poly_vertex poly_b[1000]; static struct poly_vertex poly_b[v_amt];
static uint32_t poly_bi[1000]; static uint32_t poly_bi[v_amt];
static sg_pipeline circle_pipe; static sg_pipeline circle_pipe;
static sg_bindings circle_bind; static sg_bindings circle_bind;
static sg_shader csg; static sg_shader csg;
static int circle_count = 0; static int circle_count = 0;
static int circle_vert_c = 7;
struct circle_vertex { struct circle_vertex {
float pos[2]; float pos[2];
float radius; float radius;
struct rgba color; struct rgba color;
float segsize;
float fill;
}; };
static struct circle_vertex circle_b[1000];
static struct circle_vertex circle_b[v_amt];
void debug_flush() void debug_flush()
{ {
@ -114,6 +120,12 @@ void debug_flush()
sg_apply_pipeline(line_pipe); sg_apply_pipeline(line_pipe);
sg_apply_bindings(&line_bind); sg_apply_bindings(&line_bind);
sg_apply_uniforms(SG_SHADERSTAGE_VS,0,SG_RANGE_REF(projection)); sg_apply_uniforms(SG_SHADERSTAGE_VS,0,SG_RANGE_REF(projection));
float time = lastTick;
sg_range tr = {
.ptr = &time,
.size = sizeof(float)
};
sg_apply_uniforms(SG_SHADERSTAGE_FS,0,&tr);
sg_update_buffer(line_bind.vertex_buffers[0], &(sg_range){ sg_update_buffer(line_bind.vertex_buffers[0], &(sg_range){
.ptr = line_b, .size = sizeof(struct line_vert)*line_v}); .ptr = line_b, .size = sizeof(struct line_vert)*line_v});
sg_update_buffer(line_bind.index_buffer, &(sg_range){ sg_update_buffer(line_bind.index_buffer, &(sg_range){
@ -131,11 +143,16 @@ static sg_shader_uniform_block_desc projection_ubo = {
} }
}; };
static sg_shader_uniform_block_desc time_ubo = {
.size = sizeof(float),
.uniforms = {
[0] = { .name = "time", .type = SG_UNIFORMTYPE_FLOAT },
}
};
void debugdraw_init() void debugdraw_init()
{ {
point_shader = sg_make_shader(&(sg_shader_desc){ point_shader = sg_compile_shader("shaders/point_v.glsl", "shaders/point_f.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/point_v.glsl"),
.fs.source = slurp_text("shaders/point_f.glsl"),
.vs.uniform_blocks[0] = projection_ubo .vs.uniform_blocks[0] = projection_ubo
}); });
@ -157,10 +174,9 @@ void debugdraw_init()
.usage = SG_USAGE_STREAM .usage = SG_USAGE_STREAM
}); });
line_shader = sg_make_shader(&(sg_shader_desc){ line_shader = sg_compile_shader("shaders/linevert.glsl", "shaders/linefrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/linevert.glsl"), .vs.uniform_blocks[0] = projection_ubo,
.fs.source = slurp_text("shaders/linefrag.glsl"), .fs.uniform_blocks[0] = time_ubo
.vs.uniform_blocks[0] = projection_ubo
}); });
line_pipe = sg_make_pipeline(&(sg_pipeline_desc){ line_pipe = sg_make_pipeline(&(sg_pipeline_desc){
@ -189,9 +205,7 @@ void debugdraw_init()
.type = SG_BUFFERTYPE_INDEXBUFFER .type = SG_BUFFERTYPE_INDEXBUFFER
}); });
csg = sg_make_shader(&(sg_shader_desc){ csg = sg_compile_shader("shaders/circlevert.glsl", "shaders/circlefrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/circlevert.glsl"),
.fs.source = slurp_text("shaders/circlefrag.glsl"),
.vs.uniform_blocks[0] = projection_ubo, .vs.uniform_blocks[0] = projection_ubo,
}); });
@ -203,7 +217,9 @@ void debugdraw_init()
[0].buffer_index = 1, [0].buffer_index = 1,
[1].format = SG_VERTEXFORMAT_FLOAT2, [1].format = SG_VERTEXFORMAT_FLOAT2,
[2].format = SG_VERTEXFORMAT_FLOAT, [2].format = SG_VERTEXFORMAT_FLOAT,
[3].format = SG_VERTEXFORMAT_UBYTE4N [3].format = SG_VERTEXFORMAT_UBYTE4N,
[4].format = SG_VERTEXFORMAT_FLOAT,
[5].format = SG_VERTEXFORMAT_FLOAT
}, },
.buffers[0].step_func = SG_VERTEXSTEP_PER_INSTANCE, .buffers[0].step_func = SG_VERTEXSTEP_PER_INSTANCE,
}, },
@ -214,7 +230,7 @@ void debugdraw_init()
}); });
circle_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){ circle_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(float)*circle_vert_c*5000, .size = sizeof(struct circle_vertex)*v_amt,
.usage = SG_USAGE_STREAM, .usage = SG_USAGE_STREAM,
}); });
@ -230,9 +246,7 @@ void debugdraw_init()
.usage = SG_USAGE_IMMUTABLE, .usage = SG_USAGE_IMMUTABLE,
}); });
grid_shader = sg_make_shader(&(sg_shader_desc){ grid_shader = sg_compile_shader("shaders/gridvert.glsl", "shaders/gridfrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/gridvert.glsl"),
.fs.source = slurp_text("shaders/gridfrag.glsl"),
.vs.uniform_blocks[0] = projection_ubo, .vs.uniform_blocks[0] = projection_ubo,
.vs.uniform_blocks[1] = { .vs.uniform_blocks[1] = {
.size = sizeof(float)*2, .size = sizeof(float)*2,
@ -263,9 +277,7 @@ void debugdraw_init()
grid_bind.vertex_buffers[0] = circle_bind.vertex_buffers[1]; grid_bind.vertex_buffers[0] = circle_bind.vertex_buffers[1];
poly_shader = sg_make_shader(&(sg_shader_desc){ poly_shader = sg_compile_shader("shaders/poly_v.glsl", "shaders/poly_f.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/poly_v.glsl"),
.fs.source = slurp_text("shaders/poly_f.glsl"),
.vs.uniform_blocks[0] = projection_ubo .vs.uniform_blocks[0] = projection_ubo
}); });
@ -282,27 +294,27 @@ void debugdraw_init()
}); });
poly_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){ poly_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(struct poly_vertex)*1000, .size = sizeof(struct poly_vertex)*v_amt,
.usage = SG_USAGE_STREAM, .usage = SG_USAGE_STREAM,
.type = SG_BUFFERTYPE_VERTEXBUFFER, .type = SG_BUFFERTYPE_VERTEXBUFFER,
}); });
poly_bind.index_buffer = sg_make_buffer(&(sg_buffer_desc){ poly_bind.index_buffer = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(uint32_t)*6*1000, .size = sizeof(uint32_t)*6*v_amt,
.usage = SG_USAGE_STREAM, .usage = SG_USAGE_STREAM,
.type = SG_BUFFERTYPE_INDEXBUFFER .type = SG_BUFFERTYPE_INDEXBUFFER
}); });
} }
void draw_line(cpVect *a_points, int a_n, struct rgba color, float seg_len) void draw_line(cpVect *a_points, int a_n, struct rgba color, float seg_len, int closed)
{ {
if (a_n < 2) return; if (a_n < 2) return;
int n = a_n+1;
int n = closed ? a_n+1 : a_n;
cpVect points[n]; cpVect points[n];
for (int i = 0; i < n; i++) memcpy(points, a_points, sizeof(cpVect)*n);
points[i] = a_points[i]; if (closed)
points[n-1] = a_points[0]; points[n-1] = a_points[0];
struct line_vert v[n]; struct line_vert v[n];
@ -412,11 +424,20 @@ void inflatepoints(cpVect *r, cpVect *p, float d, int n)
r[i+1] = inflatepoint(p[i],p[i+1],p[i+2], d); r[i+1] = inflatepoint(p[i],p[i+1],p[i+2], d);
} }
void draw_edge(cpVect *points, int n, struct rgba color, int thickness, int closed, int flags) void draw_edge(cpVect *points, int n, struct rgba color, int thickness, int closed, int flags, struct rgba line_color, float line_seg)
{ {
static_assert(sizeof(cpVect) == 2*sizeof(float)); static_assert(sizeof(cpVect) == 2*sizeof(float));
if (thickness == 0) {
thickness = 1;
}
/* todo: should be dashed, and filled. use a texture. */ /* todo: should be dashed, and filled. use a texture. */
/* draw polygon outline */ /* draw polygon outline */
if (cpveql(points[0], points[n-1])) {
closed = true;
n--;
}
parsl_position par_v[n]; parsl_position par_v[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
@ -427,7 +448,7 @@ void draw_edge(cpVect *points, int n, struct rgba color, int thickness, int clos
uint16_t spine_lens[] = {n}; uint16_t spine_lens[] = {n};
parsl_context *par_ctx = parsl_create_context((parsl_config){ parsl_context *par_ctx = parsl_create_context((parsl_config){
.thickness = 1, .thickness = thickness,
.flags = PARSL_FLAG_ANNOTATIONS, .flags = PARSL_FLAG_ANNOTATIONS,
.u_mode = PAR_U_MODE_DISTANCE, .u_mode = PAR_U_MODE_DISTANCE,
}); });
@ -443,26 +464,15 @@ void draw_edge(cpVect *points, int n, struct rgba color, int thickness, int clos
for (int i = 0; i < mesh->num_triangles*3; i++) for (int i = 0; i < mesh->num_triangles*3; i++)
mesh->triangle_indices[i] += poly_v; mesh->triangle_indices[i] += poly_v;
sg_range it = {
.ptr = mesh->triangle_indices,
.size = sizeof(uint32_t)*mesh->num_triangles*3
};
struct poly_vertex vertices[mesh->num_vertices]; struct poly_vertex vertices[mesh->num_vertices];
for (int i = 0; i < mesh->num_vertices; i++) { for (int i = 0; i < mesh->num_vertices; i++) {
vertices[i].pos[0] = mesh->positions[i].x; vertices[i].pos = (cpVect){ .x = mesh->positions[i].x, .y = mesh->positions[i].y };
vertices[i].pos[1] = mesh->positions[i].y;
vertices[i].uv[0] = mesh->annotations[i].u_along_curve; vertices[i].uv[0] = mesh->annotations[i].u_along_curve;
vertices[i].uv[1] = mesh->annotations[i].v_across_curve; vertices[i].uv[1] = mesh->annotations[i].v_across_curve;
vertices[i].color = color; vertices[i].color = color;
} }
sg_range vvt = {
.ptr = vertices,
.size = sizeof(struct poly_vertex)*mesh->num_vertices
};
memcpy(poly_b+poly_v, vertices, sizeof(struct poly_vertex)*mesh->num_vertices); memcpy(poly_b+poly_v, vertices, sizeof(struct poly_vertex)*mesh->num_vertices);
memcpy(poly_bi+poly_c, mesh->triangle_indices, sizeof(uint32_t)*mesh->num_triangles*3); memcpy(poly_bi+poly_c, mesh->triangle_indices, sizeof(uint32_t)*mesh->num_triangles*3);
@ -470,15 +480,35 @@ void draw_edge(cpVect *points, int n, struct rgba color, int thickness, int clos
poly_v += mesh->num_vertices; poly_v += mesh->num_vertices;
parsl_destroy_context(par_ctx); parsl_destroy_context(par_ctx);
/* Now drawing the line outlines */
if (thickness == 1) {
draw_line(points,n,line_color,line_seg, 0);
} else {
/* Draw inside and outside lines */
cpVect in_p[n];
cpVect out_p[n];
for (int i = 0, v = 0; i < n*2+1; i+=2, v++)
in_p[v] = vertices[i].pos;
for (int i = 1, v = 0; i < n*2; i+=2,v++)
out_p[v] = vertices[i].pos;
draw_line(in_p,n,line_color,line_seg,1);
draw_line(out_p,n,line_color,line_seg,1);
}
} }
void draw_circle(int x, int y, float radius, int pixels, struct rgba color, int fill) void draw_circle(int x, int y, float radius, float pixels, struct rgba color, float segsize)
{ {
struct circle_vertex cv; struct circle_vertex cv;
cv.pos[0] = x; cv.pos[0] = x;
cv.pos[1] = y; cv.pos[1] = y;
cv.radius = radius; cv.radius = radius;
cv.color = color; cv.color = color;
cv.segsize = segsize/radius;
cv.fill = pixels/radius;
memcpy(circle_b+circle_count, &cv, sizeof(struct circle_vertex)); memcpy(circle_b+circle_count, &cv, sizeof(struct circle_vertex));
circle_count++; circle_count++;
} }
@ -495,7 +525,7 @@ void draw_rect(int x, int y, int w, int h, struct rgba color)
{ .x = x-hw, .y = y+hh } { .x = x-hw, .y = y+hh }
}; };
draw_poly(verts, 4, color); draw_poly(verts, 4, color, color, 0);
} }
void draw_box(struct cpVect c, struct cpVect wh, struct rgba color) void draw_box(struct cpVect c, struct cpVect wh, struct rgba color)
@ -506,7 +536,7 @@ void draw_box(struct cpVect c, struct cpVect wh, struct rgba color)
void draw_arrow(struct cpVect start, struct cpVect end, struct rgba color, int capsize) void draw_arrow(struct cpVect start, struct cpVect end, struct rgba color, int capsize)
{ {
cpVect points[2] = {start, end}; cpVect points[2] = {start, end};
draw_line(points, 2, color, 0); draw_line(points, 2, color, 0, 0);
draw_cppoint(end, capsize, color); draw_cppoint(end, capsize, color);
} }
@ -550,11 +580,9 @@ void draw_points(struct cpVect *points, int n, float size, struct rgba color)
draw_cppoint(points[i], size, color); draw_cppoint(points[i], size, color);
} }
void draw_poly(cpVect *points, int n, struct rgba color) void draw_poly(cpVect *points, int n, struct rgba color, struct rgba line_color, float line_seg)
{ {
draw_line(points, n, color, 10); draw_line(points, n, line_color, line_seg, 1);
color.a = 40;
/* Find polygon mesh */ /* Find polygon mesh */
int tric = n - 2; int tric = n - 2;
@ -580,8 +608,7 @@ void draw_poly(cpVect *points, int n, struct rgba color)
struct poly_vertex polyverts[n]; struct poly_vertex polyverts[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
polyverts[i].pos[0] = points[i].x; polyverts[i].pos = points[i];
polyverts[i].pos[1] = points[i].y;
polyverts[i].uv[0] = 0.0; polyverts[i].uv[0] = 0.0;
polyverts[i].uv[1] = 0.0; polyverts[i].uv[1] = 0.0;
polyverts[i].color = color; polyverts[i].color = color;

View file

@ -8,15 +8,16 @@ void debugdraw_init();
void draw_cppoint(struct cpVect point, float r, struct rgba color); void draw_cppoint(struct cpVect point, float r, struct rgba color);
void draw_points(struct cpVect *points, int n, float size, struct rgba color); void draw_points(struct cpVect *points, int n, float size, struct rgba color);
void draw_line(cpVect *points, int n, struct rgba color, float seg_len); void draw_line(cpVect *points, int n, struct rgba color, float seg_len, int closed);
void draw_arrow(struct cpVect start, struct cpVect end, struct rgba, int capsize); void draw_arrow(struct cpVect start, struct cpVect end, struct rgba, int capsize);
void draw_edge(struct cpVect *points, int n, struct rgba color, int thickness, int closed, int flags); void draw_edge(struct cpVect *points, int n, struct rgba color, int thickness, int closed, int flags, struct rgba line_color, float line_seg);
void draw_circle(int x, int y, float radius, int pixels, struct rgba color, int fill); /* pixels - how many pixels thick, segsize - dashed line seg len */
void draw_circle(int x, int y, float radius, float pixels, struct rgba color, float segsize);
void draw_rect(int x, int y, int w, int h, struct rgba color); void draw_rect(int x, int y, int w, int h, struct rgba color);
void draw_box(struct cpVect c, struct cpVect wh, struct rgba color); void draw_box(struct cpVect c, struct cpVect wh, struct rgba color);
void draw_poly(cpVect *points, int n, struct rgba color); void draw_poly(cpVect *points, int n, struct rgba color, struct rgba line_color, float line_seg);
void draw_grid(int width, int span, struct rgba color); void draw_grid(int width, int span, struct rgba color);

View file

@ -32,13 +32,12 @@ char consolelog[CONSOLE_BUF+1] = {'\0'};
void mYughLog(int category, int priority, int line, const char *file, const char *message, ...) void mYughLog(int category, int priority, int line, const char *file, const char *message, ...)
{ {
#ifdef DBG
if (priority >= logLevel) { if (priority >= logLevel) {
time_t now = time(0); time_t now = time(0);
struct tm *tinfo = localtime(&now);
char timestr[50]; char timestr[50];
// strftime(timestr,50," strftime(timestr,50,"%y", tinfo);
char *dt = ctime(&now);
dt[strlen(dt) - 1] = '\0'; // The above time conversion adds a \n; this removes it
double ticks = (double)clock()/CLOCKS_PER_SEC; double ticks = (double)clock()/CLOCKS_PER_SEC;
@ -56,6 +55,7 @@ void mYughLog(int category, int priority, int line, const char *file, const char
if (priority >= 2) if (priority >= 2)
js_stacktrace(); js_stacktrace();
} }
#endif
} }
void log_print(const char *str) void log_print(const char *str)

View file

@ -16,7 +16,7 @@ extern char lastlog[];
extern char consolelog[]; extern char consolelog[];
extern int logLevel; extern int logLevel;
#if DBG #ifdef DBG
#define YughLog(cat, pri, msg, ...) mYughLog(cat, pri, __LINE__, __FILE__, msg, ##__VA_ARGS__) #define YughLog(cat, pri, msg, ...) mYughLog(cat, pri, __LINE__, __FILE__, msg, ##__VA_ARGS__)
#define YughInfo(msg, ...) mYughLog(0, 0, __LINE__, __FILE__, msg, ##__VA_ARGS__); #define YughInfo(msg, ...) mYughLog(0, 0, __LINE__, __FILE__, msg, ##__VA_ARGS__);
#define YughWarn(msg, ...) mYughLog(0, 1, __LINE__, __FILE__, msg, ##__VA_ARGS__); #define YughWarn(msg, ...) mYughLog(0, 1, __LINE__, __FILE__, msg, ##__VA_ARGS__);

View file

@ -2,7 +2,6 @@
#include "script.h" #include "script.h"
#include "2dphysics.h"
#include "anim.h" #include "anim.h"
#include "debug.h" #include "debug.h"
#include "debugdraw.h" #include "debugdraw.h"
@ -27,10 +26,16 @@
#include <assert.h> #include <assert.h>
#include <ftw.h> #include <ftw.h>
#include "render.h"
#include "model.h" #include "model.h"
#include "HandmadeMath.h"
#include "miniaudio.h" #include "miniaudio.h"
static JSValue globalThis;
#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) \ #define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \ (byte & 0x80 ? '1' : '0'), \
@ -42,6 +47,20 @@
(byte & 0x02 ? '1' : '0'), \ (byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0') (byte & 0x01 ? '1' : '0')
JSValue js_getpropstr(JSValue v, const char *str)
{
JSValue p = JS_GetPropertyStr(js,v,str);
JS_FreeValue(js,p);
return p;
}
JSValue js_getpropidx(JSValue v, uint32_t i)
{
JSValue p = JS_GetPropertyUint32(js,v,i);
JS_FreeValue(js,p);
return p;
}
int js2int(JSValue v) { int js2int(JSValue v) {
int32_t i; int32_t i;
JS_ToInt32(js, &i, v); JS_ToInt32(js, &i, v);
@ -94,7 +113,7 @@ struct timer *js2timer(JSValue v) {
double js_get_prop_number(JSValue v, const char *p) { double js_get_prop_number(JSValue v, const char *p) {
double num; double num;
JS_ToFloat64(js, &num, JS_GetPropertyStr(js, v, p)); JS_ToFloat64(js, &num, js_getpropstr(v,p));
return num; return num;
} }
@ -108,31 +127,42 @@ struct glrect js2glrect(JSValue v) {
} }
JSValue js_arridx(JSValue v, int idx) { JSValue js_arridx(JSValue v, int idx) {
return JS_GetPropertyUint32(js, v, idx); return js_getpropidx( v, idx);
} }
int js_arrlen(JSValue v) { int js_arrlen(JSValue v) {
int len; int len;
JS_ToInt32(js, &len, JS_GetPropertyStr(js, v, "length")); JS_ToInt32(js, &len, js_getpropstr( v, "length"));
return len; return len;
} }
struct rgba js2color(JSValue v) { struct rgba js2color(JSValue v) {
JSValue ja = js_arridx(v,3); JSValue c[4];
unsigned char a = JS_IsUndefined(ja) ? 255 : js2int(ja); for (int i = 0; i < 4; i++)
c[i] = js_arridx(v,i);
unsigned char a = JS_IsUndefined(c[3]) ? 255 : js2int(c[3]);
struct rgba color = { struct rgba color = {
.r = js2int(js_arridx(v,0)), .r = js2int(c[0]),
.g = js2int(js_arridx(v,1)), .g = js2int(c[1]),
.b = js2int(js_arridx(v,2)), .b = js2int(c[2]),
.a = a, .a = a,
}; };
return color; return color;
} }
HMM_Vec2 js2hmmv2(JSValue v)
{
HMM_Vec2 v2;
v2.X = js2number(js_getpropidx(v,0));
v2.Y = js2number(js_getpropidx(v,1));
return v2;
}
cpVect js2vec2(JSValue v) { cpVect js2vec2(JSValue v) {
cpVect vect; cpVect vect;
vect.x = js2number(js_arridx(v, 0)); vect.x = js2number(js_getpropidx(v,0));
vect.y = js2number(js_arridx(v, 1)); vect.y = js2number(js_getpropidx(v,1));
return vect; return vect;
} }
@ -141,7 +171,7 @@ cpBitmask js2bitmask(JSValue v) {
int len = js_arrlen(v); int len = js_arrlen(v);
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
int val = JS_ToBool(js, JS_GetPropertyUint32(js, v, i)); int val = JS_ToBool(js, js_getpropidx( v, i));
if (!val) continue; if (!val) continue;
mask |= 1 << i; mask |= 1 << i;
@ -155,7 +185,7 @@ cpVect *js2cpvec2arr(JSValue v) {
cpVect *points = NULL; cpVect *points = NULL;
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
arrput(points, js2vec2(JS_GetPropertyUint32(js, v, i))); arrput(points, js2vec2(js_getpropidx( v, i)));
return points; return points;
} }
@ -191,35 +221,35 @@ JSValue vecarr2js(cpVect *points, int n) {
JSValue duk_gui_text(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) { JSValue duk_gui_text(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) {
const char *s = JS_ToCString(js, argv[0]); const char *s = JS_ToCString(js, argv[0]);
cpVect pos = js2vec2(argv[1]); HMM_Vec2 pos = js2hmmv2(argv[1]);
float size = js2number(argv[2]); float size = js2number(argv[2]);
renderText(s, &pos, size, color_white, 500, -1); renderText(s, pos, size, color_white, 500, -1);
JS_FreeCString(js, s); JS_FreeCString(js, s);
return JS_NULL; return JS_NULL;
} }
JSValue duk_ui_text(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) { JSValue duk_ui_text(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) {
const char *s = JS_ToCString(js, argv[0]); const char *s = JS_ToCString(js, argv[0]);
cpVect pos = js2vec2(argv[1]); HMM_Vec2 pos = js2hmmv2(argv[1]);
float size = js2number(argv[2]); float size = js2number(argv[2]);
struct rgba c = js2color(argv[3]); struct rgba c = js2color(argv[3]);
int wrap = js2int(argv[4]); int wrap = js2int(argv[4]);
JSValue ret = JS_NewInt64(js, renderText(s, &pos, size, c, wrap, -1)); JSValue ret = JS_NewInt64(js, renderText(s, pos, size, c, wrap, -1));
JS_FreeCString(js, s); JS_FreeCString(js, s);
return ret; return ret;
} }
JSValue duk_cursor_text(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) { JSValue duk_cursor_text(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) {
const char *s = JS_ToCString(js, argv[0]); const char *s = JS_ToCString(js, argv[0]);
cpVect pos = js2vec2(argv[1]); HMM_Vec2 pos = js2hmmv2(argv[1]);
float size = js2number(argv[2]); float size = js2number(argv[2]);
struct rgba c = js2color(argv[3]); struct rgba c = js2color(argv[3]);
int wrap = js2int(argv[5]); int wrap = js2int(argv[5]);
int cursor = js2int(argv[4]); int cursor = js2int(argv[4]);
renderText(s, &pos, size, c, wrap, cursor); renderText(s, pos, size, c, wrap, cursor);
JS_FreeCString(js, s); JS_FreeCString(js, s);
return JS_NULL; return JS_NULL;
} }
@ -232,12 +262,13 @@ JSValue duk_gui_img(JSContext *js, JSValueConst this, int argc, JSValueConst *ar
return JS_NULL; return JS_NULL;
} }
struct nk_rect js2nk_rect(JSValue v) { struct nk_rect js2nk_rect(JSValue v) {
struct nk_rect rect; struct nk_rect rect;
rect.x = js2number(JS_GetPropertyStr(js, v, "x")); rect.x = js2number(js_getpropstr(v, "x"));
rect.y = js2number(JS_GetPropertyStr(js, v, "y")); rect.y = js2number(js_getpropstr(v, "y"));
rect.w = js2number(JS_GetPropertyStr(js, v, "w")); rect.w = js2number(js_getpropstr(v, "w"));
rect.h = js2number(JS_GetPropertyStr(js, v, "h")); rect.h = js2number(js_getpropstr(v, "h"));
return rect; return rect;
} }
@ -381,7 +412,7 @@ JSValue duk_spline_cmd(JSContext *js, JSValueConst this, int argc, JSValueConst
YughCritical("Spline creation error %d: %s", status.code, status.message); YughCritical("Spline creation error %d: %s", status.code, status.message);
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
points[i] = js2vec2(JS_GetPropertyUint32(js, ctrl_pts, i)); points[i] = js2vec2(js_getpropidx( ctrl_pts, i));
ts_bspline_set_control_points(&spline, (tsReal *)points, &status); ts_bspline_set_control_points(&spline, (tsReal *)points, &status);
@ -600,11 +631,11 @@ JSValue duk_cmd(JSContext *js, JSValueConst this, int argc, JSValueConst *argv)
break; break;
case 16: case 16:
dbg_color = js2color(argv[1]); // dbg_color = js2color(argv[1]);
break; break;
case 17: case 17:
trigger_color = js2color(argv[1]); // trigger_color = js2color(argv[1]);
break; break;
case 18: case 18:
@ -680,7 +711,7 @@ JSValue duk_cmd(JSContext *js, JSValueConst this, int argc, JSValueConst *argv)
case 37: case 37:
if (!id2sprite(js2int(argv[1]))) return JS_NULL; if (!id2sprite(js2int(argv[1]))) return JS_NULL;
vec2float(js2vec2(argv[2]), id2sprite(js2int(argv[1]))->pos); id2sprite(js2int(argv[1]))->pos = js2hmmv2(argv[2]);
break; break;
case 38: case 38:
@ -855,7 +886,7 @@ JSValue duk_cmd(JSContext *js, JSValueConst this, int argc, JSValueConst *argv)
return JS_NULL; return JS_NULL;
case 83: case 83:
draw_edge(js2cpvec2arr(argv[1]), 2, js2color(argv[2]), 1, 0, 0); draw_edge(js2cpvec2arr(argv[1]), 2, js2color(argv[2]), 1, 0, 0, js2color(argv[2]), 10);
return JS_NULL; return JS_NULL;
case 84: case 84:
@ -911,7 +942,7 @@ JSValue duk_cmd(JSContext *js, JSValueConst this, int argc, JSValueConst *argv)
break; break;
case 96: case 96:
// id2sprite(js2int(argv[1]))->color = js2color(argv[2]); id2sprite(js2int(argv[1]))->color = js2color(argv[2]);
break; break;
case 97: case 97:
@ -997,6 +1028,10 @@ JSValue duk_register(JSContext *js, JSValueConst this, int argc, JSValueConst *a
case 9: case 9:
stacktrace_callee = c; stacktrace_callee = c;
break; break;
case 10:
register_draw(c);
break;
} }
return JS_NULL; return JS_NULL;
@ -1117,6 +1152,7 @@ JSValue duk_set_body(JSContext *js, JSValueConst this, int argc, JSValueConst *a
int cmd = js2int(argv[0]); int cmd = js2int(argv[0]);
int id = js2int(argv[1]); int id = js2int(argv[1]);
struct gameobject *go = get_gameobject_from_id(id); struct gameobject *go = get_gameobject_from_id(id);
if (!go) return JS_NULL; if (!go) return JS_NULL;
/* TODO: Possible that reindexing shapes only needs done for static shapes? */ /* TODO: Possible that reindexing shapes only needs done for static shapes? */
@ -1217,12 +1253,11 @@ JSValue duk_q_body(JSContext *js, JSValueConst this, int argc, JSValueConst *arg
JSValue duk_make_sprite(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) { JSValue duk_make_sprite(JSContext *js, JSValueConst this, int argc, JSValueConst *argv) {
int go = js2int(argv[0]); int go = js2int(argv[0]);
const char *path = JS_ToCString(js, argv[1]); const char *path = JS_ToCString(js, argv[1]);
cpVect pos = js2vec2(argv[2]); HMM_Vec2 pos = js2hmmv2(argv[2]);
int sprite = make_sprite(go); int sprite = make_sprite(go);
struct sprite *sp = id2sprite(sprite); struct sprite *sp = id2sprite(sprite);
sprite_loadtex(sp, path, ST_UNIT); sprite_loadtex(sp, path, ST_UNIT);
sp->pos[0] = pos.x; sp->pos = pos;
sp->pos[1] = pos.y;
JS_FreeCString(js, path); JS_FreeCString(js, path);
@ -1360,7 +1395,7 @@ JSValue duk_make_edge2d(JSContext *js, JSValueConst this, int argc, JSValueConst
cpVect points[n]; cpVect points[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
points[i] = js2vec2(JS_GetPropertyUint32(js, argv[1], i)); points[i] = js2vec2(js_getpropidx(argv[1],i));
phys2d_edgeaddvert(edge); phys2d_edgeaddvert(edge);
phys2d_edge_setvert(edge, i, points[i]); phys2d_edge_setvert(edge, i, points[i]);
} }
@ -1418,7 +1453,7 @@ JSValue duk_anim(JSContext *js, JSValueConst this, int argc, JSValueConst *argv)
for (int i = 0; i < keyframes; i++) { for (int i = 0; i < keyframes; i++) {
struct keyframe k; struct keyframe k;
cpVect v = js2vec2(JS_GetPropertyUint32(js, argv[1], i)); cpVect v = js2vec2(js_getpropidx( argv[1], i));
k.time = v.y; k.time = v.y;
k.val = v.x; k.val = v.x;
a = anim_add_keyframe(a, k); a = anim_add_keyframe(a, k);
@ -1427,7 +1462,7 @@ JSValue duk_anim(JSContext *js, JSValueConst this, int argc, JSValueConst *argv)
for (double i = 0; i < 3.0; i = i + 0.1) { for (double i = 0; i < 3.0; i = i + 0.1) {
YughInfo("Val is now %f at time %f", anim_val(a, i), i); YughInfo("Val is now %f at time %f", anim_val(a, i), i);
JSValue vv = num2js(anim_val(a, i)); JSValue vv = num2js(anim_val(a, i));
JS_Call(js, prop, JS_GetGlobalObject(js), 1, &vv); JS_Call(js, prop, globalThis, 1, &vv);
} }
return JS_NULL; return JS_NULL;
@ -1437,15 +1472,17 @@ JSValue duk_make_timer(JSContext *js, JSValueConst this, int argc, JSValueConst
double secs = js2number(argv[1]); double secs = js2number(argv[1]);
struct callee *c = malloc(sizeof(*c)); struct callee *c = malloc(sizeof(*c));
c->fn = JS_DupValue(js, argv[0]); c->fn = JS_DupValue(js, argv[0]);
c->obj = JS_GetGlobalObject(js); c->obj = JS_DupValue(js, globalThis);
int id = timer_make(secs, call_callee, c, 1); int id = timer_make(secs, call_callee, c, 1);
return JS_NewInt64(js, id); return JS_NewInt64(js, id);
} }
#define DUK_FUNC(NAME, ARGS) JS_SetPropertyStr(js, JS_GetGlobalObject(js), #NAME, JS_NewCFunction(js, duk_##NAME, #NAME, ARGS)); #define DUK_FUNC(NAME, ARGS) JS_SetPropertyStr(js, globalThis, #NAME, JS_NewCFunction(js, duk_##NAME, #NAME, ARGS));
void ffi_load() { void ffi_load() {
globalThis = JS_GetGlobalObject(js);
DUK_FUNC(yughlog, 4) DUK_FUNC(yughlog, 4)
DUK_FUNC(nuke, 6) DUK_FUNC(nuke, 6)
DUK_FUNC(make_gameobject, 7) DUK_FUNC(make_gameobject, 7)

View file

@ -18,6 +18,8 @@
#include "stb_rect_pack.h" #include "stb_rect_pack.h"
#include "stb_truetype.h" #include "stb_truetype.h"
#include "HandmadeMath.h"
struct sFont *font; struct sFont *font;
#define max_chars 40000 #define max_chars 40000
@ -82,9 +84,7 @@ struct text_vert {
static struct text_vert text_buffer[max_chars]; static struct text_vert text_buffer[max_chars];
void font_init(struct shader *textshader) { void font_init(struct shader *textshader) {
fontshader = sg_make_shader(&(sg_shader_desc){ fontshader = sg_compile_shader("shaders/textvert.glsl", "shaders/textfrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/textvert.glsl"),
.fs.source = slurp_text("shaders/textfrag.glsl"),
.vs.uniform_blocks[0] = { .vs.uniform_blocks[0] = {
.size = sizeof(float) * 16, .size = sizeof(float) * 16,
// .layout = SG_UNIFORMLAYOUT_STD140, // .layout = SG_UNIFORMLAYOUT_STD140,
@ -133,6 +133,31 @@ void font_init(struct shader *textshader) {
bind_text.fs_images[0] = font->texID; bind_text.fs_images[0] = font->texID;
} }
struct sFont *MakeSDFFont(const char *fontfile, int height)
{
YughInfo("Making sdf font %s.", fontfile);
int packsize = 1024;
struct sFont *newfont = calloc(1, sizeof(struct sFont));
newfont->height = height;
char fontpath[256];
snprintf(fontpath, 256, "fonts/%s", fontfile);
unsigned char *ttf_buffer = slurp_file(fontpath);
unsigned char *bitmap = malloc(packsize * packsize);
stbtt_fontinfo fontinfo;
if (!stbtt_InitFont(&fontinfo, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer, 0))) {
YughError("Failed to make font %s", fontfile);
}
for (int i = 32; i < 95; i++) {
int w, h, xoff, yoff;
// unsigned char *stbtt_GetGlyphSDF(&fontinfo, height, i, 1, 0, 1, &w, &h, &xoff, &yoff);
}
}
struct sFont *MakeFont(const char *fontfile, int height) { struct sFont *MakeFont(const char *fontfile, int height) {
YughInfo("Making font %s.", fontfile); YughInfo("Making font %s.", fontfile);
@ -151,7 +176,9 @@ struct sFont *MakeFont(const char *fontfile, int height) {
stbtt_pack_context pc; stbtt_pack_context pc;
stbtt_PackBegin(&pc, bitmap, packsize, packsize, 0, 1, NULL); int pad = 2;
stbtt_PackBegin(&pc, bitmap, packsize, packsize, 0, pad, NULL);
stbtt_PackFontRange(&pc, ttf_buffer, 0, height, 32, 95, glyphs); stbtt_PackFontRange(&pc, ttf_buffer, 0, height, 32, 95, glyphs);
stbtt_PackEnd(&pc); stbtt_PackEnd(&pc);
@ -181,10 +208,10 @@ struct sFont *MakeFont(const char *fontfile, int height) {
stbtt_packedchar glyph = glyphs[c - 32]; stbtt_packedchar glyph = glyphs[c - 32];
struct glrect r; struct glrect r;
r.s0 = glyph.x0 / (float)packsize; r.s0 = (glyph.x0) / (float)packsize;
r.s1 = glyph.x1 / (float)packsize; r.s1 = (glyph.x1) / (float)packsize;
r.t0 = glyph.y0 / (float)packsize; r.t0 = (glyph.y0) / (float)packsize;
r.t1 = glyph.y1 / (float)packsize; r.t1 = (glyph.y1) / (float)packsize;
newfont->Characters[c].Advance = glyph.xadvance; newfont->Characters[c].Advance = glyph.xadvance;
newfont->Characters[c].Size[0] = glyph.x1 - glyph.x0; newfont->Characters[c].Size[0] = glyph.x1 - glyph.x0;
@ -229,19 +256,23 @@ void text_flush() {
static int drawcaret = 0; static int drawcaret = 0;
void sdrawCharacter(struct Character c, mfloat_t cursor[2], float scale, struct rgba color) { void sdrawCharacter(struct Character c, HMM_Vec2 cursor, float scale, struct rgba color) {
float offset[2] = {-1, 1}; HMM_Vec2 offset = {0.0};
struct text_vert vert; struct text_vert vert;
vert.wh.x = c.Size[0] * scale; float lsize = 1.0 / 1024.0;
vert.wh.y = c.Size[1] * scale;
vert.pos.x = cursor[0] - (c.Bearing[0] + offset[0]) * scale; float oline = 1.0;
vert.pos.y = cursor[1] - (c.Bearing[1] + offset[1]) * scale;
vert.uv.u = c.rect.s0*USHRT_MAX; vert.pos.x = cursor.X - (c.Bearing[0] + offset.X) * scale - oline;
vert.uv.v = c.rect.t0*USHRT_MAX; vert.pos.y = cursor.Y - (c.Bearing[1] + offset.Y) * scale - oline;
vert.st.u = (c.rect.s1-c.rect.s0)*USHRT_MAX; vert.wh.x = c.Size[0] * scale + (oline*2);
vert.st.v = (c.rect.t1-c.rect.t0)*USHRT_MAX; vert.wh.y = c.Size[1] * scale + (oline*2);
vert.uv.u = (c.rect.s0 - oline*lsize)*USHRT_MAX;
vert.uv.v = (c.rect.t0 - oline*lsize)*USHRT_MAX;
vert.st.u = (c.rect.s1-c.rect.s0+oline*lsize*2.0)*USHRT_MAX;
vert.st.v = (c.rect.t1-c.rect.t0+oline*lsize*2.0)*USHRT_MAX;
vert.color = color; vert.color = color;
memcpy(text_buffer + curchar, &vert, sizeof(struct text_vert)); memcpy(text_buffer + curchar, &vert, sizeof(struct text_vert));
@ -277,13 +308,11 @@ void text_settype(struct sFont *mfont) {
font = mfont; font = mfont;
} }
int renderText(const char *text, mfloat_t pos[2], float scale, struct rgba color, float lw, int caret) { int renderText(const char *text, HMM_Vec2 pos, float scale, struct rgba color, float lw, int caret) {
int len = strlen(text); int len = strlen(text);
drawcaret = caret; drawcaret = caret;
mfloat_t cursor[2] = {0.f}; HMM_Vec2 cursor = pos;
cursor[0] = pos[0];
cursor[1] = pos[1];
const unsigned char *line, *wordstart, *drawstart; const unsigned char *line, *wordstart, *drawstart;
line = drawstart = (unsigned char *)text; line = drawstart = (unsigned char *)text;
@ -293,12 +322,12 @@ int renderText(const char *text, mfloat_t pos[2], float scale, struct rgba color
while (*line != '\0') { while (*line != '\0') {
if (isblank(*line)) { if (isblank(*line)) {
sdrawCharacter(font->Characters[*line], cursor, scale, usecolor); sdrawCharacter(font->Characters[*line], cursor, scale, usecolor);
cursor[0] += font->Characters[*line].Advance * scale; cursor.X += font->Characters[*line].Advance * scale;
line++; line++;
} else if (isspace(*line)) { } else if (isspace(*line)) {
sdrawCharacter(font->Characters[*line], cursor, scale, usecolor); sdrawCharacter(font->Characters[*line], cursor, scale, usecolor);
cursor[1] -= scale * font->height; cursor.Y -= scale * font->height;
cursor[0] = pos[0]; cursor.X = pos.X;
line++; line++;
} else { } else {
@ -311,14 +340,14 @@ int renderText(const char *text, mfloat_t pos[2], float scale, struct rgba color
line++; line++;
} }
if (lw > 0 && (cursor[0] + wordWidth - pos[0]) >= lw) { if (lw > 0 && (cursor.X + wordWidth - pos.X) >= lw) {
cursor[0] = pos[0]; cursor.X = pos.X;
cursor[1] -= scale * font->height; cursor.Y -= scale * font->height;
} }
while (wordstart < line) { while (wordstart < line) {
sdrawCharacter(font->Characters[*wordstart], cursor, scale, usecolor); sdrawCharacter(font->Characters[*wordstart], cursor, scale, usecolor);
cursor[0] += font->Characters[*wordstart].Advance * scale; cursor.X += font->Characters[*wordstart].Advance * scale;
wordstart++; wordstart++;
} }
} }
@ -328,5 +357,5 @@ int renderText(const char *text, mfloat_t pos[2], float scale, struct rgba color
} }
*/ */
return cursor[1] - pos[1]; return cursor.Y - pos.Y;
} }

View file

@ -1,18 +1,18 @@
#ifndef FONT_H #ifndef FONT_H
#define FONT_H #define FONT_H
#include "mathc.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
#include "texture.h" #include "texture.h"
#include "2dphysics.h" #include "2dphysics.h"
#include "HandmadeMath.h"
struct shader; struct shader;
struct window; struct window;
/// Holds all state information relevant to a character as loaded using FreeType /// Holds all state information relevant to a character as loaded using FreeType
struct Character { struct Character {
mfloat_t Size[2]; // Size of glyph float Size[2]; // Size of glyph
mfloat_t Bearing[2]; // Offset from baseline to left/top of glyph float Bearing[2]; // Offset from baseline to left/top of glyph
unsigned int Advance; // Horizontal offset to advance to next glyph unsigned int Advance; // Horizontal offset to advance to next glyph
struct glrect rect; struct glrect rect;
}; };
@ -26,9 +26,9 @@ struct sFont {
void font_init(struct shader *s); void font_init(struct shader *s);
struct sFont *MakeFont(const char *fontfile, int height); struct sFont *MakeFont(const char *fontfile, int height);
void sdrawCharacter(struct Character c, mfloat_t cursor[2], float scale, struct rgba color); void sdrawCharacter(struct Character c, HMM_Vec2 cursor, float scale, struct rgba color);
void text_settype(struct sFont *font); void text_settype(struct sFont *font);
int renderText(const char *text, mfloat_t pos[2], float scale, struct rgba color, float lw, int caret); int renderText(const char *text, HMM_Vec2 pos, float scale, struct rgba color, float lw, int caret);
// void text_frame(); // void text_frame();
void text_flush(); void text_flush();

View file

@ -89,12 +89,11 @@ void go_shape_apply(cpBody *body, cpShape *shape, struct gameobject *go) {
cpShapeSetElasticity(shape, go->e); cpShapeSetElasticity(shape, go->e);
cpShapeSetCollisionType(shape, go2id(go)); cpShapeSetCollisionType(shape, go2id(go));
/* cpShapeFilter filter; cpShapeFilter filter;
filter.group = go2id(go); filter.group = go2id(go);
filter.categories = 1<<go->layer; filter.categories = CP_ALL_CATEGORIES;//1<<go->layer;
filter.mask = category_masks[go->layer]; filter.mask = CP_ALL_CATEGORIES;//category_masks[go->layer];
cpShapeSetFilter(shape, filter); cpShapeSetFilter(shape, filter);
*/
} }
void go_shape_moi(cpBody *body, cpShape *shape, struct gameobject *go) { void go_shape_moi(cpBody *body, cpShape *shape, struct gameobject *go) {
@ -106,6 +105,7 @@ void go_shape_moi(cpBody *body, cpShape *shape, struct gameobject *go) {
} }
moment += s->moi(s->data, go->mass); moment += s->moi(s->data, go->mass);
if (moment < 0) moment = 0;
cpBodySetMoment(go->body, moment); cpBodySetMoment(go->body, moment);
} }

View file

@ -3,7 +3,6 @@
#include "2dphysics.h" #include "2dphysics.h"
#include "config.h" #include "config.h"
#include "mathc.h"
#include <chipmunk/chipmunk.h> #include <chipmunk/chipmunk.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -23,13 +23,21 @@ struct shader *wireframeShader = NULL;
struct shader *animSpriteShader = NULL; struct shader *animSpriteShader = NULL;
static struct shader *textShader; static struct shader *textShader;
mfloat_t editorClearColor[4] = {0.2f, 0.4f, 0.3f, 1.f}; struct rgba editorClearColor = {35,60,92,255};
float shadowLookahead = 8.5f; float shadowLookahead = 8.5f;
mfloat_t gridSmallColor[3] = {0.35f, 1.f, 0.9f}; struct rgba gridSmallColor = {
.r = 255 * 0.35f,
.g = 255,
.b = 255 * 0.9f
};
mfloat_t gridBigColor[3] = {0.92f, 0.92f, 0.68f}; struct rgba gridBigColor = {
.r = 255 * 0.92f,
.g = 255 * 0.92f,
.b = 255 * 0.68f
};
float gridScale = 500.f; float gridScale = 500.f;
float smallGridUnit = 1.f; float smallGridUnit = 1.f;
@ -38,9 +46,6 @@ float gridSmallThickness = 2.f;
float gridBigThickness = 7.f; float gridBigThickness = 7.f;
float gridOpacity = 0.3f; float gridOpacity = 0.3f;
mfloat_t proj[16];
// Debug render modes // Debug render modes
bool renderGizmos = false; bool renderGizmos = false;
bool showGrid = true; bool showGrid = true;
@ -92,6 +97,19 @@ static struct {
sg_image depth_img; sg_image depth_img;
} crt_post; } crt_post;
void make_shader(sg_shader_desc *d, sg_shader result, void *data)
{
}
void fail_shader(sg_shader id, void *data)
{
}
static sg_trace_hooks hooks = {
.fail_shader = fail_shader,
.make_shader = make_shader
};
void openglInit() { void openglInit() {
if (!mainwin) { if (!mainwin) {
@ -99,22 +117,21 @@ void openglInit() {
exit(1); exit(1);
} }
sg_trace_hooks hh = sg_install_trace_hooks(&hooks);
font_init(NULL); font_init(NULL);
debugdraw_init(); debugdraw_init();
sprite_initialize(); sprite_initialize();
nuke_init(mainwin); nuke_init(mainwin);
model_init(); model_init();
// duck = MakeModel("sponza.glb"); sg_color c;
rgba2floats(&c, editorClearColor);
pass_action = (sg_pass_action){ pass_action = (sg_pass_action){
.colors[0] = {.action = SG_ACTION_CLEAR, .value = {editorClearColor[1], editorClearColor[2], editorClearColor[3], 1.f}}, .colors[0] = {.action = SG_ACTION_CLEAR, .value = c}
}; };
crt_post.shader = sg_make_shader(&(sg_shader_desc){ crt_post.shader = sg_compile_shader("shaders/postvert.glsl", "shaders/crtfrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/postvert.glsl"),
.fs.source = slurp_text("shaders/crtfrag.glsl"),
.fs.images[0] = { .fs.images[0] = {
.name = "diffuse_texture", .name = "diffuse_texture",
.image_type = SG_IMAGETYPE_2D, .image_type = SG_IMAGETYPE_2D,
@ -177,8 +194,6 @@ void openglInit() {
shadow_desc.pixel_format = SG_PIXELFORMAT_DEPTH; shadow_desc.pixel_format = SG_PIXELFORMAT_DEPTH;
ddimg = sg_make_image(&shadow_desc); ddimg = sg_make_image(&shadow_desc);
// duck = MakeModel("sponza.glb");
sg_shadow.pass = sg_make_pass(&(sg_pass_desc){ sg_shadow.pass = sg_make_pass(&(sg_pass_desc){
.color_attachments[0].image = depth_img, .color_attachments[0].image = depth_img,
.depth_stencil_attachment.image = ddimg, .depth_stencil_attachment.image = ddimg,
@ -187,9 +202,7 @@ void openglInit() {
sg_shadow.pass_action = (sg_pass_action) { sg_shadow.pass_action = (sg_pass_action) {
.colors[0] = { .action=SG_ACTION_CLEAR, .value = {1,1,1,1} } }; .colors[0] = { .action=SG_ACTION_CLEAR, .value = {1,1,1,1} } };
sg_shadow.shader = sg_make_shader(&(sg_shader_desc){ sg_shadow.shader = sg_compile_shader("shaders/shadowvert.glsl", "shaders/shadowfrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/shadowvert.glsl"),
.fs.source = slurp_text("shaders/shadowfrag.glsl"),
.vs.uniform_blocks[0] = { .vs.uniform_blocks[0] = {
.size = sizeof(float) * 16 * 2, .size = sizeof(float) * 16 * 2,
.uniforms = { .uniforms = {
@ -217,6 +230,34 @@ void openglInit() {
}); });
*/ */
}
void render_winsize()
{
sg_destroy_image(crt_post.img);
sg_destroy_image(crt_post.depth_img);
sg_destroy_pass(crt_post.pass);
crt_post.img = sg_make_image(&(sg_image_desc){
.render_target = true,
.width = mainwin->width,
.height = mainwin->height
});
crt_post.depth_img = sg_make_image(&(sg_image_desc){
.render_target = true,
.width = mainwin->width,
.height = mainwin->height,
.pixel_format = SG_PIXELFORMAT_DEPTH_STENCIL
});
crt_post.pass = sg_make_pass(&(sg_pass_desc){
.color_attachments[0].image = crt_post.img,
.depth_stencil_attachment.image = crt_post.depth_img,
});
crt_post.bind.fs_images[0] = crt_post.img;
} }
static cpBody *camera = NULL; static cpBody *camera = NULL;
@ -233,8 +274,8 @@ float cam_zoom() { return zoom; }
void add_zoom(float val) { zoom = val; } void add_zoom(float val) { zoom = val; }
mfloat_t projection[16] = {0.f}; HMM_Mat4 projection = {0.f};
float hudproj[16] = {0.f}; HMM_Mat4 hudproj = {0.f};
HMM_Vec3 dirl_pos = {4, 100, 20}; HMM_Vec3 dirl_pos = {4, 100, 20};
@ -278,21 +319,25 @@ void openglRender(struct window *window) {
//////////// 2D projection //////////// 2D projection
cpVect pos = cam_pos(); cpVect pos = cam_pos();
mat4_ortho(projection, pos.x - zoom * window->width / 2, projection = HMM_Orthographic_RH_NO(
pos.x - zoom * window->width / 2,
pos.x + zoom * window->width / 2, pos.x + zoom * window->width / 2,
pos.y - zoom * window->height / 2, pos.y - zoom * window->height / 2,
pos.y + zoom * window->height / 2, -1.f, 1.f); pos.y + zoom * window->height / 2, -1.f, 1.f);
mat4_ortho(hudproj, 0, window->width, 0, window->height, -1.f, 1.f); hudproj = HMM_Orthographic_RH_NO(0, window->width, 0, window->height, -1.f, 1.f);
sprite_draw_all(); sprite_draw_all();
sprite_flush(); sprite_flush();
//// DEBUG call_draw();
if (debugDrawPhysics)
gameobject_draw_debugs();
//// DEBUG
if (debugDrawPhysics) {
gameobject_draw_debugs();
call_debugs(); call_debugs();
}
debug_flush(); debug_flush();
////// TEXT && GUI ////// TEXT && GUI
@ -315,3 +360,19 @@ void openglRender(struct window *window) {
sg_commit(); sg_commit();
} }
sg_shader sg_compile_shader(const char *v, const char *f, sg_shader_desc *d)
{
YughWarn("Making shader with %s and %s", v, f);
char *vs = slurp_text(v);
char *fs = slurp_text(f);
d->vs.source = vs;
d->fs.source = fs;
sg_shader ret = sg_make_shader(d);
free(vs);
free(fs);
return ret;
}

View file

@ -18,16 +18,16 @@ extern int renderMode;
extern HMM_Vec3 dirl_pos; extern HMM_Vec3 dirl_pos;
extern float projection[16]; extern HMM_Mat4 projection;
extern float hudproj[16]; extern HMM_Mat4 hudproj;
extern float gridScale; extern float gridScale;
extern float smallGridUnit; extern float smallGridUnit;
extern float bigGridUnit; extern float bigGridUnit;
extern float gridSmallThickness; extern float gridSmallThickness;
extern float gridBigThickness; extern float gridBigThickness;
extern float gridBigColor[]; extern struct rgba gridBigColor;
extern float gridSmallColor[]; extern struct rgba gridSmallColor;
extern float gridOpacity; extern float gridOpacity;
extern float editorFOV; extern float editorFOV;
extern float shadowLookahead; extern float shadowLookahead;
@ -53,6 +53,8 @@ void opengl_rendermode(enum RenderMode r);
void openglInit3d(struct window *window); void openglInit3d(struct window *window);
void openglRender3d(struct window *window, struct mCamera *camera); void openglRender3d(struct window *window, struct mCamera *camera);
void render_winsize();
void debug_draw_phys(int draw); void debug_draw_phys(int draw);
void set_cam_body(cpBody *body); void set_cam_body(cpBody *body);
@ -60,4 +62,6 @@ cpVect cam_pos();
float cam_zoom(); float cam_zoom();
void add_zoom(float val); void add_zoom(float val);
sg_shader sg_compile_shader(const char *v, const char *f, sg_shader_desc *d);
#endif #endif

View file

@ -16,6 +16,22 @@ struct st_n {
struct uv_n t; struct uv_n t;
}; };
struct rgba {
unsigned char r;
unsigned char g;
unsigned char b;
unsigned char a;
};
static float *rgba2floats(float *r, struct rgba c)
{
r[0] = c.r / 255.0;
r[1] = c.g / 255.0;
r[2] = c.b / 255.0;
r[3] = c.a / 255.0;
return r;
}
static sg_blend_state blend_trans = { static sg_blend_state blend_trans = {
.enabled = true, .enabled = true,
.src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA, .src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA,
@ -24,5 +40,4 @@ static sg_blend_state blend_trans = {
.src_factor_alpha = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA .src_factor_alpha = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA
}; };
#endif #endif

View file

@ -17,6 +17,12 @@
JSContext *js = NULL; JSContext *js = NULL;
JSRuntime *rt = NULL; JSRuntime *rt = NULL;
#ifdef DBG
#define JS_EVAL_FLAGS JS_EVAL_FLAG_STRICT
#else
#define JS_EVAL_FLAGS JS_EVAL_FLAG_STRICT | JS_EVAL_FLAG_STRIP
#endif
static int load_prefab(const char *fpath, const struct stat *sb, int typeflag) { static int load_prefab(const char *fpath, const struct stat *sb, int typeflag) {
if (typeflag != FTW_F) if (typeflag != FTW_F)
return 0; return 0;
@ -38,6 +44,9 @@ JSValue num_cache[100] = {0};
void script_init() { void script_init() {
/* Load all prefabs into memory */ /* Load all prefabs into memory */
// if (DBG)
// script_dofile("scripts/debug.js");
// else
script_dofile("scripts/engine.js"); script_dofile("scripts/engine.js");
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)
@ -45,7 +54,19 @@ void script_init() {
} }
void script_run(const char *script) { void script_run(const char *script) {
JS_FreeValue(js, JS_Eval(js, script, strlen(script), "script", 0)); JS_FreeValue(js, JS_Eval(js, script, strlen(script), "script", JS_EVAL_FLAGS));
}
void compile_script(const char *file) {
const char *script = slurp_text(file);
JSValue obj = JS_Eval(js, script, strlen(script), file, JS_EVAL_FLAG_COMPILE_ONLY | JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAGS);
size_t out_len;
uint8_t *out;
out = JS_WriteObject(js, &out_len, obj, JS_WRITE_OBJ_BYTECODE);
FILE *f = fopen("out.jsc", "w");
fwrite(out, sizeof out[0], out_len, f);
fclose(f);
} }
struct callee stacktrace_callee; struct callee stacktrace_callee;
@ -57,34 +78,23 @@ time_t file_mod_secs(const char *file) {
} }
void js_stacktrace() { void js_stacktrace() {
#ifdef DBG
call_callee(&stacktrace_callee); call_callee(&stacktrace_callee);
return; #endif
} }
void js_dump_stack() { void js_dump_stack() {
js_stacktrace(); js_stacktrace();
return;
JSValue exception = JS_GetException(js);
if (JS_IsNull(exception)) return;
JSValue val = JS_GetPropertyStr(js, exception, "stack");
if (!JS_IsUndefined(val)) {
const char *name = JS_ToCString(js, JS_GetPropertyStr(js, exception, "name"));
const char *msg = JS_ToCString(js, JS_GetPropertyStr(js, exception, "message"));
const char *stack = JS_ToCString(js, val);
YughError("%s :: %s\n%s", name, msg, stack);
JS_FreeCString(js, name);
JS_FreeCString(js, msg);
JS_FreeCString(js, stack);
}
} }
int js_print_exception(JSValue v) { int js_print_exception(JSValue v) {
#ifdef DBG
if (JS_IsException(v)) { if (JS_IsException(v)) {
JSValue exception = JS_GetException(js); JSValue exception = JS_GetException(js);
/* TODO: Does it need freed if null? */
if (JS_IsNull(exception))
return 0;
JSValue val = JS_GetPropertyStr(js, exception, "stack"); JSValue val = JS_GetPropertyStr(js, exception, "stack");
if (!JS_IsUndefined(val)) {
const char *name = JS_ToCString(js, JS_GetPropertyStr(js, exception, "name")); const char *name = JS_ToCString(js, JS_GetPropertyStr(js, exception, "name"));
const char *msg = JS_ToCString(js, JS_GetPropertyStr(js, exception, "message")); const char *msg = JS_ToCString(js, JS_GetPropertyStr(js, exception, "message"));
const char *stack = JS_ToCString(js, val); const char *stack = JS_ToCString(js, val);
@ -93,11 +103,12 @@ int js_print_exception(JSValue v) {
JS_FreeCString(js, name); JS_FreeCString(js, name);
JS_FreeCString(js, msg); JS_FreeCString(js, msg);
JS_FreeCString(js, stack); JS_FreeCString(js, stack);
} JS_FreeValue(js,val);
JS_FreeValue(js,exception);
return 1; return 1;
} }
#endif
return 0; return 0;
} }
@ -108,7 +119,7 @@ int script_dofile(const char *file) {
YughError("Can't find file %s.", file); YughError("Can't find file %s.", file);
return 0; return 0;
} }
JSValue obj = JS_Eval(js, script, strlen(script), file, 0); JSValue obj = JS_Eval(js, script, strlen(script), file, JS_EVAL_FLAGS);
js_print_exception(obj); js_print_exception(obj);
JS_FreeValue(js, obj); JS_FreeValue(js, obj);
@ -119,7 +130,7 @@ int script_dofile(const char *file) {
s is the function to call on that object s is the function to call on that object
*/ */
void script_eval_w_env(const char *s, JSValue env) { void script_eval_w_env(const char *s, JSValue env) {
JSValue v = JS_EvalThis(js, env, s, strlen(s), "internal", 0); JSValue v = JS_EvalThis(js, env, s, strlen(s), "internal", JS_EVAL_FLAGS);
js_print_exception(v); js_print_exception(v);
JS_FreeValue(js, v); JS_FreeValue(js, v);
} }
@ -186,4 +197,8 @@ void call_physics(double dt) { callee_dbl(physupdate_callee, dt); }
struct callee debug_callee; struct callee debug_callee;
void register_debug(struct callee c) { debug_callee = c; } void register_debug(struct callee c) { debug_callee = c; }
void call_debugs() { JS_Call(js, debug_callee.fn, debug_callee.obj, 0, NULL); } void call_debugs() { call_callee(&debug_callee); }
static struct callee draw_callee;
void register_draw(struct callee c) { draw_callee = c; }
void call_draw() { call_callee(&draw_callee); }

View file

@ -51,4 +51,8 @@ void unregister_obj(JSValue obj);
void register_physics(struct callee c); void register_physics(struct callee c);
void call_physics(double dt); void call_physics(double dt);
void register_draw(struct callee c);
void call_draw();
void compile_script(const char *file);
#endif #endif

View file

@ -116,62 +116,9 @@ void shader_compile(struct shader *shader) {
void shader_use(struct shader *shader) { void shader_use(struct shader *shader) {
// glUseProgram(shader->id); // glUseProgram(shader->id);
} }
/*
void shader_setbool(struct shader *shader, const char *name, int val)
{
glUniform1i(glGetUniformLocation(shader->id, name), val);
}
void shader_setint(struct shader *shader, const char *name, int val)
{
glUniform1i(glGetUniformLocation(shader->id, name), val);
}
void shader_setfloat(struct shader *shader, const char *name, float val)
{
glUniform1f(glGetUniformLocation(shader->id, name), val);
}
void shader_setvec2(struct shader *shader, const char *name, mfloat_t val[2])
{
glUniform2fv(glGetUniformLocation(shader->id, name), 1, val);
}
void shader_setvec4(struct shader *shader, const char *name, mfloat_t val[4])
{
glUniform4fv(glGetUniformLocation(shader->id, name), 1, val);
}
void shader_setmat2(struct shader *shader, const char *name, mfloat_t val[4])
{
glUniformMatrix2fv(glGetUniformLocation(shader->id, name), 1, GL_FALSE, val);
}
void shader_setmat3(struct shader *shader, const char *name, mfloat_t val[9])
{
glUniformMatrix3fv(glGetUniformLocation(shader->id, name), 1, GL_FALSE, val);
}
void shader_setmat4(struct shader *shader, const char *name, mfloat_t val[16])
{
glUniformMatrix4fv(glGetUniformLocation(shader->id, name), 1, GL_FALSE, val);
}
void shader_setUBO(struct shader *shader, const char *name, unsigned int index)
{
glUniformBlockBinding(shader->id, glGetUniformBlockIndex(shader->id, name), index);
}
*/
void shader_compile_all() { void shader_compile_all() {
for (int i = 0; i < arrlen(shaders); i++) for (int i = 0; i < arrlen(shaders); i++)
shader_compile(&shaders[i]); shader_compile(&shaders[i]);
} }
void shader_setvec3(struct shader *shader, const char *name, mfloat_t val[3]) {
// glUniform3fv(glGetUniformLocation(shader->id, name), 1, val);
}
void shader_setmat4(struct shader *shader, const char *name, mfloat_t val[16]) {
// glUniformMatrix4fv(glGetUniformLocation(shader->id, name), 1, GL_FALSE, val);
}

View file

@ -1,7 +1,6 @@
#ifndef SHADER_H #ifndef SHADER_H
#define SHADER_H #define SHADER_H
#include "mathc.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
struct shader { struct shader {
@ -14,18 +13,4 @@ void shader_compile_all();
struct shader *MakeShader(const char *vertpath, const char *fragpath); struct shader *MakeShader(const char *vertpath, const char *fragpath);
void shader_compile(struct shader *shader); void shader_compile(struct shader *shader);
void shader_use(struct shader *shader); void shader_use(struct shader *shader);
/*
void shader_setbool(struct shader *shader, const char *name, int val);
void shader_setint(struct shader *shader, const char *name, int val);
void shader_setfloat(struct shader *shader, const char *name, float val);
void shader_setvec2(struct shader *shader, const char *name, mfloat_t val[2]);
void shader_setvec3(struct shader *shader, const char *name, mfloat_t val[3]);
void shader_setvec4(struct shader *shader, const char *name, mfloat_t val[4]);
void shader_setmat2(struct shader *shader, const char *name, mfloat_t val[4]);
void shader_setmat3(struct shader *shader, const char *name, mfloat_t val[9]);
void shader_setmat4(struct shader *shader, const char *name, mfloat_t val[16]);
void shader_setUBO(struct shader *shader, const char *name, unsigned int index);
*/
#endif #endif

View file

@ -23,7 +23,7 @@ static int sprite_c = 0;
int make_sprite(int go) { int make_sprite(int go) {
struct sprite sprite = { struct sprite sprite = {
.color = {1.f, 1.f, 1.f}, .color = color_white,
.size = {1.f, 1.f}, .size = {1.f, 1.f},
.tex = texture_loadfromfile(NULL), .tex = texture_loadfromfile(NULL),
.go = go, .go = go,
@ -92,9 +92,8 @@ void sprite_draw_all() {
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
arrfree(layers[i]); arrfree(layers[i]);
for (int i = 0; i < arrlen(sprites); i++) { for (int i = 0; i < arrlen(sprites); i++)
if (sprites[i].go >= 0 && sprites[i].enabled) arrpush(layers[sprites[i].layer], &sprites[i]); if (sprites[i].go >= 0 && sprites[i].enabled) arrpush(layers[sprites[i].layer], &sprites[i]);
}
for (int i = 4; i >= 0; i--) for (int i = 4; i >= 0; i--)
for (int j = 0; j < arrlen(layers[i]); j++) for (int j = 0; j < arrlen(layers[i]); j++)
@ -114,9 +113,7 @@ void sprite_settex(struct sprite *sprite, struct Texture *tex) {
sg_shader shader_sprite; sg_shader shader_sprite;
void sprite_initialize() { void sprite_initialize() {
shader_sprite = sg_make_shader(&(sg_shader_desc){ shader_sprite = sg_compile_shader("shaders/spritevert.glsl", "shaders/spritefrag.glsl", &(sg_shader_desc){
.vs.source = slurp_text("shaders/spritevert.glsl"),
.fs.source = slurp_text("shaders/spritefrag.glsl"),
.vs.uniform_blocks[0] = { .vs.uniform_blocks[0] = {
.size = 64, .size = 64,
.layout = SG_UNIFORMLAYOUT_STD140, .layout = SG_UNIFORMLAYOUT_STD140,
@ -136,7 +133,13 @@ void sprite_initialize() {
.attrs = { .attrs = {
[0].format = SG_VERTEXFORMAT_FLOAT4}}, [0].format = SG_VERTEXFORMAT_FLOAT4}},
.primitive_type = SG_PRIMITIVETYPE_TRIANGLE_STRIP, .primitive_type = SG_PRIMITIVETYPE_TRIANGLE_STRIP,
.label = "sprite pipeline"}); .label = "sprite pipeline",
/* .depth = {
.write_enabled = true,
.compare = SG_COMPAREFUNC_LESS_EQUAL
}
*/
});
bind_sprite.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){ bind_sprite.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(float) * 16 * 500, .size = sizeof(float) * 16 * 500,
@ -146,24 +149,27 @@ void sprite_initialize() {
}); });
} }
void tex_draw(struct Texture *tex, float pos[2], float angle, float size[2], float offset[2], struct glrect r, float color[3]) { void tex_draw(struct Texture *tex, HMM_Vec2 pos, float angle, HMM_Vec2 size, HMM_Vec2 offset, struct glrect r, struct rgba color) {
float model[16] = {0.f}; HMM_Mat4 model = HMM_M4D(1.0);
mfloat_t r_model[16] = {0.f}; HMM_Mat4 r_model = HMM_M4D(1.0);
memcpy(model, UNITMAT4, sizeof(UNITMAT4));
memcpy(r_model, UNITMAT4, sizeof(UNITMAT4));
mfloat_t t_scale[2] = {tex->width * st_s_w(r) * size[0], tex->height * st_s_h(r) * size[1]}; HMM_Vec3 t_scale = {
mfloat_t t_offset[2] = {offset[0] * t_scale[0] * size[0], offset[1] * t_scale[1] * size[1]}; tex->width * st_s_w(r) * size.X,
tex->height * st_s_h(r) * size.Y,
t_scale.Z = 1.0};
mat4_translate_vec2(model, t_offset); HMM_Vec3 t_offset = {
offset.X * t_scale.X,
offset.Y * t_scale.Y,
0.0};
mat4_scale_vec2(model, t_scale); HMM_Translate_p(&model, t_offset);
mat4_rotation_z(r_model, angle); HMM_Scale_p(&model, t_scale);
r_model = HMM_Rotate_RH(angle, vZ);
model = HMM_MulM4(r_model, model);
HMM_Translate_p(&model, (HMM_Vec3){pos.X, pos.Y, 0.0});
mat4_multiply(model, r_model, model); model = HMM_MulM4(projection, model);
mat4_translate_vec2(model, pos);
mat4_multiply(model, projection, model);
float vertices[] = { float vertices[] = {
0.f, 0.f, r.s0, r.t1, 0.f, 0.f, r.s0, r.t1,
@ -174,12 +180,15 @@ void tex_draw(struct Texture *tex, float pos[2], float angle, float size[2], flo
bind_sprite.fs_images[0] = tex->id; bind_sprite.fs_images[0] = tex->id;
sg_append_buffer(bind_sprite.vertex_buffers[0], SG_RANGE_REF(vertices)); sg_append_buffer(bind_sprite.vertex_buffers[0], SG_RANGE_REF(vertices));
sg_apply_bindings(&bind_sprite); sg_apply_bindings(&bind_sprite);
sg_apply_uniforms(SG_SHADERSTAGE_VS, 0, SG_RANGE_REF(model)); sg_apply_uniforms(SG_SHADERSTAGE_VS, 0, SG_RANGE_REF(model.Elements));
sg_range c = { float cl[3] = {
.ptr = color, color.r / 255.0,
.size = sizeof(float) * 3}; color.g / 255.0,
sg_apply_uniforms(SG_SHADERSTAGE_FS, 0, &c); color.b / 255.0
};
sg_apply_uniforms(SG_SHADERSTAGE_FS, 0, SG_RANGE_REF(cl));
sg_draw(sprite_count * 4, 4, 1); sg_draw(sprite_count * 4, 4, 1);
sprite_count++; sprite_count++;
@ -190,8 +199,8 @@ void sprite_draw(struct sprite *sprite) {
if (sprite->tex) { if (sprite->tex) {
cpVect cpos = cpBodyGetPosition(go->body); cpVect cpos = cpBodyGetPosition(go->body);
float pos[2] = {cpos.x, cpos.y}; HMM_Vec2 pos = {cpos.x, cpos.y};
float size[2] = {sprite->size[0] * go->scale * go->flipx, sprite->size[1] * go->scale * go->flipy}; HMM_Vec2 size = {sprite->size.X * go->scale * go->flipx, sprite->size.Y * go->scale * go->flipy};
tex_draw(sprite->tex, pos, cpBodyGetAngle(go->body), size, sprite->pos, sprite->frame, sprite->color); tex_draw(sprite->tex, pos, cpBodyGetAngle(go->body), size, sprite->pos, sprite->frame, sprite->color);
} }
} }
@ -205,25 +214,24 @@ void sprite_setanim(struct sprite *sprite, struct TexAnim *anim, int frame) {
void gui_draw_img(const char *img, float x, float y) { void gui_draw_img(const char *img, float x, float y) {
sg_apply_pipeline(pip_sprite); sg_apply_pipeline(pip_sprite);
struct Texture *tex = texture_loadfromfile(img); struct Texture *tex = texture_loadfromfile(img);
float pos[2] = {x, y}; HMM_Vec2 pos = {x, y};
float size[2] = {1.f, 1.f}; HMM_Vec2 size = {1.f, 1.f};
float offset[2] = {0.f, 0.f}; HMM_Vec2 offset = {0.f, 0.f};
float white[3] = {1.f, 1.f, 1.f}; tex_draw(tex, pos, 0.f, size, offset, tex_get_rect(tex), color_white);
tex_draw(tex, pos, 0.f, size, offset, tex_get_rect(tex), white);
} }
void sprite_setframe(struct sprite *sprite, struct glrect *frame) { void sprite_setframe(struct sprite *sprite, struct glrect *frame) {
sprite->frame = *frame; sprite->frame = *frame;
} }
void video_draw(struct datastream *ds, HMM_Vec2 pos, HMM_Vec2 size, float rotate, struct rgba color)
void video_draw(struct datastream *stream, mfloat_t position[2], mfloat_t size[2], float rotate, mfloat_t color[3]) { {
// shader_use(vid_shader); // shader_use(vid_shader);
/*
static mfloat_t model[16]; static mfloat_t model[16];
memcpy(model, UNITMAT4, sizeof(UNITMAT4)); memcpy(model, UNITMAT4, sizeof(UNITMAT4));
mat4_translate_vec2(model, position); mat4_translate_vec2(model, position);
mat4_scale_vec2(model, size); mat4_scale_vec2(model, size);
*/
// shader_setmat4(vid_shader, "model", model); // shader_setmat4(vid_shader, "model", model);
// shader_setvec3(vid_shader, "spriteColor", color); // shader_setvec3(vid_shader, "spriteColor", color);
/* /*

View file

@ -3,18 +3,19 @@
#include <stdio.h> #include <stdio.h>
#include "timer.h" #include "timer.h"
#include "mathc.h"
#include "texture.h" #include "texture.h"
#include "HandmadeMath.h"
#include "render.h"
struct datastream; struct datastream;
struct gameobject; struct gameobject;
struct sprite { struct sprite {
mfloat_t pos[2]; HMM_Vec2 pos;
mfloat_t size[2]; HMM_Vec2 size;
float rotation; float rotation;
mfloat_t color[3]; struct rgba color;
int go; int go;
int id; int id;
struct Texture *tex; struct Texture *tex;
@ -35,7 +36,7 @@ void sprite_setanim(struct sprite *sprite, struct TexAnim *anim, int frame);
void sprite_setframe(struct sprite *sprite, struct glrect *frame); void sprite_setframe(struct sprite *sprite, struct glrect *frame);
void sprite_initialize(); void sprite_initialize();
void sprite_draw(struct sprite *sprite); void sprite_draw(struct sprite *sprite);
void video_draw(struct datastream *ds, mfloat_t pos[2], mfloat_t size[2], float rotate, mfloat_t color[3]); void video_draw(struct datastream *ds, HMM_Vec2 pos, HMM_Vec2 size, float rotate, struct rgba color);
void sprite_draw_all(); void sprite_draw_all();
unsigned int incrementAnimFrame(unsigned int interval, struct sprite *sprite); unsigned int incrementAnimFrame(unsigned int interval, struct sprite *sprite);
void sprite_flush(); void sprite_flush();

View file

@ -25,10 +25,23 @@ struct Texture *texture_notex() {
return texture_pullfromfile("./icons/no_tex.png"); return texture_pullfromfile("./icons/no_tex.png");
} }
unsigned int next_pow2(unsigned int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
int mip_levels(int width, int height) int mip_levels(int width, int height)
{ {
int levels = 0; int levels = 0;
while ( width > 1 && height > 1 )
while (width > 1 || height > 1)
{ {
width >>= 1; width >>= 1;
height >>= 1; height >>= 1;
@ -37,6 +50,20 @@ int mip_levels(int width, int height)
return levels; return levels;
} }
int mip_wh(int w, int h, int *mw, int *mh, int lvl)
{
w >>= lvl;
h >>= lvl;
if (w == 0 && h == 0)
return 1;
*mw = w ? w : 1;
*mh = h ? h : 1;
return 0;
}
/* If an empty string or null is put for path, loads default texture */ /* If an empty string or null is put for path, loads default texture */
struct Texture *texture_pullfromfile(const char *path) { struct Texture *texture_pullfromfile(const char *path) {
if (!path) return texture_notex(); if (!path) return texture_notex();
@ -58,6 +85,10 @@ struct Texture *texture_pullfromfile(const char *path) {
YughError("STBI failed to load file %s with message: %s\nOpening default instead.", path, stbi_failure_reason()); YughError("STBI failed to load file %s with message: %s\nOpening default instead.", path, stbi_failure_reason());
return texture_notex(); return texture_notex();
} }
unsigned int nw = next_pow2(tex->width);
unsigned int nh = next_pow2(tex->height);
tex->data = data; tex->data = data;
int filter; int filter;
@ -71,6 +102,8 @@ struct Texture *texture_pullfromfile(const char *path) {
int mips = mip_levels(tex->width, tex->height)+1; int mips = mip_levels(tex->width, tex->height)+1;
YughInfo("Has %d mip levels, from wxh %dx%d, pow2 is %ux%u.", mips, tex->width, tex->height,nw,nh);
int mipw, miph; int mipw, miph;
mipw = tex->width; mipw = tex->width;
miph = tex->height; miph = tex->height;
@ -81,9 +114,9 @@ struct Texture *texture_pullfromfile(const char *path) {
mipdata[0] = data; mipdata[0] = data;
for (int i = 1; i < mips; i++) { for (int i = 1; i < mips; i++) {
int w, h; int w, h, mipw, miph;
w = mipw>>1; mip_wh(tex->width, tex->height, &mipw, &miph, i-1); /* mipw miph are previous iteration */
h = miph>>1; mip_wh(tex->width, tex->height, &w, &h, i);
mipdata[i] = malloc(w * h * 4); mipdata[i] = malloc(w * h * 4);
stbir_resize_uint8(mipdata[i-1], mipw, miph, 0, mipdata[i], w, h, 0, 4); stbir_resize_uint8(mipdata[i-1], mipw, miph, 0, mipdata[i], w, h, 0, 4);
sg_img_data.subimage[0][i] = (sg_range){ .ptr = mipdata[i], .size = w*h*4 }; sg_img_data.subimage[0][i] = (sg_range){ .ptr = mipdata[i], .size = w*h*4 };

View file

@ -68,6 +68,11 @@ struct Texture {
struct TexAnim anim; struct TexAnim anim;
}; };
struct Image {
struct Texture *tex;
struct glrect frame;
};
struct Texture *texture_pullfromfile(const char *path); // Create texture from image struct Texture *texture_pullfromfile(const char *path); // Create texture from image
struct Texture *texture_loadfromfile(const char *path); // Create texture & load to gpu struct Texture *texture_loadfromfile(const char *path); // Create texture & load to gpu
void texture_sync(const char *path); void texture_sync(const char *path);

View file

@ -1,44 +1,50 @@
#include "transform.h" #include "transform.h"
#include <string.h> #include <string.h>
struct mTransform MakeTransform(mfloat_t pos[3], mfloat_t rotation[4], float scale) { struct mTransform MakeTransform(HMM_Vec3 pos, HMM_Quat rotation, float scale)
struct mTransform newT; {
memcpy(newT.position, pos, sizeof(*pos)); struct mTransform newT = {
memcpy(newT.rotation, rotation, sizeof(*rotation)); .pos = pos,
newT.scale = scale; .rotation = rotation,
.scale = scale
};
return newT; return newT;
} }
mfloat_t *trans_forward(mfloat_t *res, HMM_Vec3 trans_forward(const struct mTransform *const trans)
const struct mTransform *const trans) { {
// YughLog(0, SDL_LOG_PRIORITY_WARN, "Rotation is %f", trans->rotation[0]); return HMM_QVRot(vFWD, trans->rotation);
return vec3_rotate_quat(res, FORWARD, trans->rotation);
} }
mfloat_t *trans_back(mfloat_t *res, const struct mTransform *trans) { HMM_Vec3 trans_back(const struct mTransform *trans)
return vec3_rotate_quat(res, BACK, trans->rotation); {
return HMM_QVRot(vBKWD, trans->rotation);
} }
mfloat_t *trans_up(mfloat_t *res, const struct mTransform *trans) { HMM_Vec3 trans_up(const struct mTransform *trans)
return vec3_rotate_quat(res, UP, trans->rotation); {
return HMM_QVRot(vUP, trans->rotation);
} }
mfloat_t *trans_down(mfloat_t *res, const struct mTransform *trans) { HMM_Vec3 trans_down(const struct mTransform *trans)
return vec3_rotate_quat(res, DOWN, trans->rotation); {
return HMM_QVRot(vDOWN, trans->rotation);
} }
mfloat_t *trans_right(mfloat_t *res, const struct mTransform *trans) { HMM_Vec3 trans_right(const struct mTransform *trans)
return vec3_rotate_quat(res, RIGHT, trans->rotation); {
return HMM_QVRot(vRIGHT, trans->rotation);
} }
mfloat_t *trans_left(mfloat_t *res, const struct mTransform *trans) { HMM_Vec3 trans_left(const struct mTransform *trans)
return vec3_rotate_quat(res, LEFT, trans->rotation); {
return HMM_QVRot(vLEFT, trans->rotation);
} }
#include "nuke.h" #include "nuke.h"
void trans_drawgui(struct mTransform *T) { void trans_drawgui(struct mTransform *T) {
nuke_property_float3("Position", -1000.f, T->position, 1000.f, 1.f, 1.f); nuke_property_float3("Position", -1000.f, T->pos.Elements, 1000.f, 1.f, 1.f);
nuke_property_float3("Rotation", 0.f, T->rotation, 360.f, 1.f, 0.1f); nuke_property_float3("Rotation", 0.f, T->rotation.Elements, 360.f, 1.f, 0.1f);
nuke_property_float("Scale", 0.f, &T->scale, 1000.f, 0.1f, 0.1f); nuke_property_float("Scale", 0.f, &T->scale, 1000.f, 0.1f, 0.1f);
} }

View file

@ -1,23 +1,23 @@
#ifndef TRANSFORM_H #ifndef TRANSFORM_H
#define TRANSFORM_H #define TRANSFORM_H
#include "mathc.h" #include "HandmadeMath.h"
struct mTransform { struct mTransform {
mfloat_t position[3]; HMM_Vec3 pos;
mfloat_t rotation[4]; HMM_Quat rotation;
float scale; float scale;
}; };
struct mTransform MakeTransform(mfloat_t pos[3], mfloat_t rotation[3], float scale); struct mTransform MakeTransform(HMM_Vec3 pos, HMM_Quat rotation, float scale);
mfloat_t *trans_forward(mfloat_t * res, const struct mTransform *const trans); HMM_Vec3 trans_forward(const struct mTransform *const trans);
mfloat_t *trans_back(mfloat_t * res, const struct mTransform *trans); HMM_Vec3 trans_back(const struct mTransform *trans);
mfloat_t *trans_up(mfloat_t * res, const struct mTransform *trans); HMM_Vec3 trans_up(const struct mTransform *trans);
mfloat_t *trans_down(mfloat_t * res, const struct mTransform *trans); HMM_Vec3 trans_down(const struct mTransform *trans);
mfloat_t *trans_right(mfloat_t * res, const struct mTransform *trans); HMM_Vec3 trans_right(const struct mTransform *trans);
mfloat_t *trans_left(mfloat_t * res, const struct mTransform *trans); HMM_Vec3 trans_left(const struct mTransform *trans);
void trans_drawgui(struct mTransform *T); void trans_drawgui(struct mTransform *T);
//extern Serialize *make_transform(); //extern Serialize *make_transform();

View file

@ -23,6 +23,7 @@ int is_win(struct window *s, GLFWwindow *w) {
} }
void window_size_callback(GLFWwindow *w, int width, int height) { void window_size_callback(GLFWwindow *w, int width, int height) {
render_winsize();
} }
struct window *winfind(GLFWwindow *w) { struct window *winfind(GLFWwindow *w) {

View file

@ -42,12 +42,12 @@ double physlag = 0;
double updatelag = 0; double updatelag = 0;
double renderMS = 1 / 165.f; double renderMS = 1 / 165.f;
double physMS = 1 / 120.f; double physMS = 1 / 240.f;
double updateMS = 1 / 60.f; double updateMS = 1 / 60.f;
static int ed = 1; static int ed = 1;
static int sim_play = 0; static int sim_play = 0;
static double lastTick; double lastTick = 0.0;
static int phys_step = 0; static int phys_step = 0;
static float timescale = 1.f; static float timescale = 1.f;
@ -90,17 +90,6 @@ void seghandle(int sig) {
#endif #endif
} }
void compile_script(const char *file) {
const char *script = slurp_text(file);
JSValue obj = JS_Eval(js, script, strlen(script), file, JS_EVAL_FLAG_COMPILE_ONLY | JS_EVAL_TYPE_GLOBAL);
size_t out_len;
uint8_t *out;
out = JS_WriteObject(js, &out_len, obj, JS_WRITE_OBJ_BYTECODE);
FILE *f = fopen("out.jsc", "w");
fwrite(out, sizeof out[0], out_len, f);
fclose(f);
}
void sg_logging(const char *tag, uint32_t lvl, uint32_t id, const char *msg, uint32_t line, const char *file, void *data) { void sg_logging(const char *tag, uint32_t lvl, uint32_t id, const char *msg, uint32_t line, const char *file, void *data) {
mYughLog(0, 1, line, file, "tag: %s, msg: %s", tag, msg); mYughLog(0, 1, line, file, "tag: %s, msg: %s", tag, msg);
@ -195,6 +184,7 @@ int main(int argc, char **args) {
.func = sg_logging, .func = sg_logging,
.user_data = NULL, .user_data = NULL,
}, },
.buffer_pool_size = 1024, .buffer_pool_size = 1024,
.context.sample_count = 1, .context.sample_count = 1,
}); });
@ -207,6 +197,7 @@ int main(int argc, char **args) {
else else
script_dofile("scripts/play.js"); script_dofile("scripts/play.js");
while (!want_quit()) { while (!want_quit()) {
double elapsed = glfwGetTime() - lastTick; double elapsed = glfwGetTime() - lastTick;
deltaT = elapsed; deltaT = elapsed;

View file

@ -13,5 +13,7 @@ void print_stacktrace();
int frame_fps(); int frame_fps();
extern double lastTick;
#endif #endif

View file

@ -1,3 +1,18 @@
var fns = [
() => {
var ttt = {};
Object.defineProperty(ttt, 'a', {});
ttt.a = 5;
},
() => { Log.warn("did it"); }
];
//fns.forEach(x => x());
/* Prototypes out an object and extends with values */ /* Prototypes out an object and extends with values */
function clone(proto, binds) { function clone(proto, binds) {
var c = Object.create(proto); var c = Object.create(proto);
@ -265,6 +280,13 @@ value: function(b) {
return c; return c;
}}); }});
Object.defineProperty(Array.prototype, 'mult', {
value: function(arr) {
var c = [];
for (var i = 0; i < this.length; i++) { c[i] = this[i] * arr[i]; }
return c;
}});
Object.defineProperty(Array.prototype, 'apply', { Object.defineProperty(Array.prototype, 'apply', {
value: function(fn) { value: function(fn) {
this.forEach(function(x) { x[fn].apply(x); }); this.forEach(function(x) { x[fn].apply(x); });

View file

@ -134,6 +134,7 @@ var char2d = clone(sprite, {
var frameslice = 1/frames; var frameslice = 1/frames;
rect.s0 = frameslice*frame; rect.s0 = frameslice*frame;
rect.s1 = frameslice*(frame+1); rect.s1 = frameslice*(frame+1);
return rect; return rect;
}, },
@ -147,7 +148,8 @@ var char2d = clone(sprite, {
char.timer = timer.make(char.advance.bind(char), 1/char.curplaying.fps); char.timer = timer.make(char.advance.bind(char), 1/char.curplaying.fps);
char.timer.loop = true; char.timer.loop = true;
char.obscure('timer'); char.obscure('timer');
char.obscure('rect'); // char.obscure('rect');
char.rect = {};
char.setsprite(); char.setsprite();
return char; return char;
}, },

View file

@ -6,7 +6,6 @@ var Gizmos = {
}, },
}; };
var Debug = { var Debug = {
draw_grid(width, span, color) { draw_grid(width, span, color) {
color = color ? color : Color.green; color = color ? color : Color.green;
@ -160,3 +159,10 @@ var Nuke = {
Object.defineProperty(Nuke, "curwin", {enumerable:false}); Object.defineProperty(Nuke, "curwin", {enumerable:false});
Object.defineProperty(Nuke, "defaultrect", {enumerable:false}); Object.defineProperty(Nuke, "defaultrect", {enumerable:false});
var DebugControls = {
input_f1_pressed() {
Debug.draw_phys(!Debug.phys_drawing);
},
};
set_pawn(DebugControls);

View file

@ -64,9 +64,10 @@ function dainty_assign(target, source)
target[key] = source[key]; target[key] = source[key];
else if (typeof target[key] === 'object') else if (typeof target[key] === 'object')
dainty_assign(target[key], source[key]); dainty_assign(target[key], source[key]);
else else {
target[key] = source[key]; target[key] = source[key];
} }
}
}; };
/* Deeply remove source keys from target, not removing objects */ /* Deeply remove source keys from target, not removing objects */

View file

@ -1,4 +1,20 @@
"use strict"; var files = {};
function load(file) {
if (typeof Log !== 'undefined')
Log.warn(`doing ${file}`);
var modtime = cmd(0, file);
if (modtime === 0) {
Log.stack();
return false;
}
files[file] = modtime;
}
load("scripts/base.js");
var Log = { var Log = {
set level(x) { cmd(92,x); }, set level(x) { cmd(92,x); },
@ -57,20 +73,8 @@ var Log = {
}; };
var files = {};
function load(file) {
var modtime = cmd(0, file);
if (modtime === 0) {
Log.stack();
return false;
}
files[file] = modtime;
}
load("scripts/base.js");
load("scripts/diff.js"); load("scripts/diff.js");
load("scripts/debug.js");
function win_icon(str) { function win_icon(str) {
cmd(90, str); cmd(90, str);
@ -507,6 +511,11 @@ var Register = {
Player.players.forEach(x => x.uncontrol(obj)); Player.players.forEach(x => x.uncontrol(obj));
}, },
draws: [],
draw() {
this.draws.forEach(x => x[0].call(x[1]));
},
}; };
Register.unregister_obj(null); Register.unregister_obj(null);
@ -518,6 +527,7 @@ register(6, Register.debug, Register);
register(7, Register.kbm_input, Register); register(7, Register.kbm_input, Register);
register(8, Register.gamepad_input, Register); register(8, Register.gamepad_input, Register);
register(9, Log.stack, this); register(9, Log.stack, this);
register(10, Register.draw, Register);
Register.gamepad_playermap[0] = Player.players[0]; Register.gamepad_playermap[0] = Player.players[0];
@ -549,6 +559,10 @@ function unregister_nk_gui(fn, obj) {
Register.nk_guis = Register.nk_guis.filter(x => x[0] !== fn && x[1] !== obj); Register.nk_guis = Register.nk_guis.filter(x => x[0] !== fn && x[1] !== obj);
}; };
function register_draw(fn,obj) {
Register.draws.push([fn, obj ? obj : this]);
}
register_update(Yugine.exec, Yugine); register_update(Yugine.exec, Yugine);
/* These functions are the "defaults", and give control to player0 */ /* These functions are the "defaults", and give control to player0 */
@ -560,6 +574,8 @@ function unset_pawn(obj, player = Player.players[0]) {
player.uncontrol(obj); player.uncontrol(obj);
} }
var Signal = { var Signal = {
signals: [], signals: [],
obj_begin(fn, obj, go) { obj_begin(fn, obj, go) {
@ -597,6 +613,7 @@ function reloadfiles() {
Object.keys(files).forEach(function (x) { load(x); }); Object.keys(files).forEach(function (x) { load(x); });
} }
load("scripts/debug.js");
function Color(from) { function Color(from) {
var color = Object.create(Array); var color = Object.create(Array);
@ -760,7 +777,7 @@ var Level = {
this[x.varname] = x; this[x.varname] = x;
} }
},this); },this);
Log.warn("eval script");
eval(this.script); eval(this.script);
if (typeof extern === 'object') if (typeof extern === 'object')
@ -970,6 +987,8 @@ var Level = {
if (!file.endsWith(".lvl")) file = file + ".lvl"; if (!file.endsWith(".lvl")) file = file + ".lvl";
var newlevel = Level.create(); var newlevel = Level.create();
Log.warn(`MAKING LEVEL ${file}`);
if (IO.exists(file)) { if (IO.exists(file)) {
newlevel.filejson = IO.slurp(file); newlevel.filejson = IO.slurp(file);
@ -979,6 +998,7 @@ var Level = {
} catch (e) { } catch (e) {
newlevel.ed_gizmo = function() { GUI.text("Invalid level file: " + newlevel.file, world2screen(newlevel.pos), 1, Color.red); }; newlevel.ed_gizmo = function() { GUI.text("Invalid level file: " + newlevel.file, world2screen(newlevel.pos), 1, Color.red); };
newlevel.selectable = false; newlevel.selectable = false;
throw e;
} }
newlevel.file = file; newlevel.file = file;
newlevel.dirty = false; newlevel.dirty = false;
@ -1020,7 +1040,7 @@ var Level = {
if (typeof objs === 'object') if (typeof objs === 'object')
objs = objs.array(); objs = objs.array();
objs.forEach(function(x) { objs.forEach(x => {
if (x.from === 'group') { if (x.from === 'group') {
var loadedlevel = Level.loadfile(x.file); var loadedlevel = Level.loadfile(x.file);
if (!loadedlevel) { if (!loadedlevel) {
@ -1054,10 +1074,14 @@ var Level = {
var newobj = this.spawn(gameobjects[x.from]); var newobj = this.spawn(gameobjects[x.from]);
delete x.from;
dainty_assign(newobj, x); dainty_assign(newobj, x);
if (x._pos) if (x._pos)
newobj.pos = x._pos; newobj.pos = x._pos;
if (x._angle) if (x._angle)
newobj.angle = x._angle; newobj.angle = x._angle;
for (var key in newobj.components) for (var key in newobj.components)
@ -1066,7 +1090,7 @@ var Level = {
newobj.sync(); newobj.sync();
created.push(newobj); created.push(newobj);
}, this); });
created.forEach(function(x) { created.forEach(function(x) {
if (x.varname) if (x.varname)
@ -1244,6 +1268,7 @@ var gameobject = {
if (x < 0) x = 0; if (x < 0) x = 0;
if (x > 4) x = 4; if (x > 4) x = 4;
this._draw_layer = x; this._draw_layer = x;
this.sync();
}, },
_draw_layer_nuke() { _draw_layer_nuke() {
Nuke.label("Draw layer"); Nuke.label("Draw layer");
@ -1500,6 +1525,8 @@ var gameobject = {
Register.unregister_obj(this.components[key]); Register.unregister_obj(this.components[key]);
this.components[key].kill(); this.components[key].kill();
} }
this.stop();
}, },
prop_obj() { prop_obj() {
@ -1580,7 +1607,7 @@ var gameobject = {
} }
}; };
if (typeof obj.update !== 'undefined') if (typeof obj.update === 'function')
register_update(obj.update, obj); register_update(obj.update, obj);
if (typeof obj.physupdate === 'function') if (typeof obj.physupdate === 'function')
@ -1592,6 +1619,9 @@ var gameobject = {
if (typeof obj.separate === 'function') if (typeof obj.separate === 'function')
obj.register_separate(obj.separate, obj); obj.register_separate(obj.separate, obj);
if (typeof obj.draw === 'function')
register_draw(obj.draw,obj);
obj.components.forEach(function(x) { obj.components.forEach(function(x) {
if (typeof x.collide === 'function') if (typeof x.collide === 'function')
register_collide(1, x.collide, x, obj.body, x.shape); register_collide(1, x.collide, x, obj.body, x.shape);

View file

@ -3,25 +3,36 @@ in vec2 coords;
out vec4 color; out vec4 color;
in float radius; in float radius;
in vec4 fcolor; in vec4 fcolor;
in vec2 pos; in vec2 pos;
in float segsize;
in float fill;
#define PI 3.14
void main() void main()
{ {
int thickness = 1; float px = 1/radius;
bool fill = false;
// int tt = thickness + 1;
float R1 = 1.f; float R1 = 1.f;
// float R2 = 1.f - (thickness*zoom / radius); float R2 = 1.0 - fill;
float R2 = 1.f - (thickness/radius); float dist = sqrt(pow(coords.x,2) + pow(coords.y,2));
float dist = sqrt(dot(coords, coords));
if (dist >= R2 && dist <= R1)
color = fcolor; color = fcolor;
else if (dist < R2)
color = vec4(fcolor.xyz, 0.1f); // if (dist < R2 || dist > R1)
else // discard;
float sm = 1 - smoothstep(R1-px,R1,dist);
float sm2 = smoothstep(R2-px,R2,dist);
float a = sm*sm2;
color = mix(vec4(0,0,0,0), fcolor, a);
if (segsize<0)
return;
float f = atan(coords.y, coords.x) + PI;
if (mod(f, segsize) < segsize/2)
discard; discard;
} }

View file

@ -3,19 +3,25 @@ layout (location = 0) in vec2 vertex;
layout (location = 1) in vec2 apos; layout (location = 1) in vec2 apos;
layout (location = 2) in float aradius; layout (location = 2) in float aradius;
layout (location = 3) in vec4 acolor; layout (location = 3) in vec4 acolor;
//layout (location = 4) in float afill; layout (location = 4) in float asegsize;
layout (location = 5) in float afill;
out vec2 coords; out vec2 coords;
out float radius;
out vec4 fcolor; out vec4 fcolor;
out float segsize;
out float fill;
out float radius;
uniform mat4 proj; uniform mat4 proj;
void main() void main()
{ {
gl_Position = proj * vec4((vertex * aradius) + apos, 0.0, 1.0); gl_Position = proj * vec4((vertex * aradius) + apos, 0.0, 1.0);
coords = vertex.xy; coords = vertex;
fcolor = acolor; fcolor = acolor;
segsize = asegsize;
fill = afill;
radius = aradius; radius = aradius;
} }

View file

@ -7,10 +7,12 @@ uniform sampler2D diffuse_texture;
void main() void main()
{ {
vec2 screensize = textureSize(diffuse_texture,0);
vec4 color = texture(diffuse_texture, TexCoords); vec4 color = texture(diffuse_texture, TexCoords);
// float avg = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b; float avg = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
// frag_color = vec4(avg,avg,avg,1.0); frag_color = vec4(avg,avg,avg,1.0);
float lc = 720.0/2.0; float lc = screensize.y/2.0;
float line = TexCoords.y * lc; float line = TexCoords.y * lc;
float line_intensity = mod(float(line),2); float line_intensity = mod(float(line),2);
@ -22,5 +24,4 @@ void main()
float b = color.b; float b = color.b;
frag_color = vec4(r, g*0.99, b, 1.0) * clamp(line_intensity, 0.85, 1.0); frag_color = vec4(r, g*0.99, b, 1.0) * clamp(line_intensity, 0.85, 1.0);
frag_color = texture(diffuse_texture, TexCoords);
} }

View file

@ -9,10 +9,14 @@ float pat = 0.5;
int pp = 0x0C24; int pp = 0x0C24;
uniform float time;
void main() void main()
{ {
color = fcolor; color = fcolor;
if (mod(dist,seg_len)/seg_len < 0.5) if (seg_len == 0) return;
if (mod(dist+time*seg_len,seg_len)/seg_len < 0.5)
discard; discard;
/* /*
int d = int(dist); int d = int(dist);

View file

@ -1,6 +1,7 @@
#version 330 core #version 330 core
in vec2 TexCoords; in vec2 TexCoords;
in vec4 fColor; in vec4 fColor;
in vec2 fst;
out vec4 color; out vec4 color;
@ -12,10 +13,35 @@ void main()
{ {
float lettera = texture(text,TexCoords).r; float lettera = texture(text,TexCoords).r;
// color = vec4(1.f, 1.f, 1.f, texture(text, TexCoords).r);
if (lettera <= 0.1f) if (lettera <= 0.1f)
discard; {
vec2 uvpos = TexCoords - fst;
color = vec4(fColor.xyz, lettera * fColor.a); for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
float pa = texture(text, uvpos + (fst*vec2(x,y))).r;
if (pa > 0.1) {
color = vec4(0.0,0.0,0.0, fColor.a);
return;
}
}
}
discard;
}
// vec2 lsize = fst / textureSize(text,0).xy;
/* vec2 uvpos = TexCoords - fst;
for (int x = 0; x < 3; x++) {
for (int y = 0; 0 < 3; y++) {
float pa = texture(text, uvpos + (fst * vec2(x,y))).r;
if (pa <= 0.1) {
color = vec4(0.0,0.0,0.0,fColor.a);
return;
}
}
}
*/
color = vec4(fColor.xyz, fColor.a);
} }

View file

@ -8,6 +8,7 @@ layout (location = 5) in vec4 vColor;
out vec2 TexCoords; out vec2 TexCoords;
out vec4 fColor; out vec4 fColor;
out vec2 fst;
uniform mat4 projection; uniform mat4 projection;
@ -16,6 +17,7 @@ void main()
gl_Position = projection * vec4(pos + (vert * wh), 0.0, 1.0); gl_Position = projection * vec4(pos + (vert * wh), 0.0, 1.0);
TexCoords = uv + vec2(vert.x*st.x, st.y - vert.y*st.y); TexCoords = uv + vec2(vert.x*st.x, st.y - vert.y*st.y);
fst = st / wh;
fColor = vColor; fColor = vColor;
} }