Compare commits

...

8 commits

26 changed files with 386 additions and 58 deletions

22
assets/shaders/font.fs Normal file
View file

@ -0,0 +1,22 @@
#version 330 core
out vec4 FragColor;
in vec3 vPos;
in vec2 vTexCoord;
uniform sampler2D fontTex;
uniform int charIndex;
// Main
void main() {
int x = (charIndex-32) % 16;
int y = (charIndex-32) / 16;
float fx = float(x) / 16;
float fy = float(y) / 8;
vec4 color = texture(fontTex, vec2(fx, fy) + vTexCoord * vec2(1.f/32, 1.f/16));
FragColor = vec3(color) == vec3(0, 0, 0) ? vec4(0, 0, 0, 0) : color;
// FragColor = color;
}

12
assets/shaders/font.vs Normal file
View file

@ -0,0 +1,12 @@
#version 330 core
in vec3 aPos;
in vec2 aTexCoord;
out vec3 vPos;
out vec2 vTexCoord;
void main()
{
gl_Position = vec4(aPos, 1.0);
vPos = aPos;
vTexCoord = aTexCoord;
}

View file

@ -4,10 +4,10 @@
out vec4 FragColor;
uniform vec3 aColor;
uniform vec4 aColor;
// Main
void main() {
FragColor = vec4(aColor, 1);
FragColor = aColor;
}

1
assets/textures/NOTE.txt Normal file
View file

@ -0,0 +1 @@
debugfnt.bmp is Iosevka NFM Thin generated via CBFG

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

View file

@ -20,7 +20,6 @@ void Rotate::buildJoint() {
if ((!GetParent() || GetParent().value()->GetClass() != &JointsService::TYPE) && !workspace()) return;
std::shared_ptr<Workspace> workspace = workspaceOfPart(part0.lock()).value();
if (!workspace->physicsWorld) return;
// Update Part1's rotation and cframe prior to creating the joint as reactphysics3d locks rotation based on how it
// used to be rather than specifying an anchor rotation, so whatever.
@ -29,7 +28,7 @@ void Rotate::buildJoint() {
workspace->SyncPartPhysics(part1.lock());
// Do NOT use Abs() in this scenario. For some reason that breaks it
rp::HingeJointInfo jointInfo(part0.lock()->rigidBody, part1.lock()->rigidBody, (part0.lock()->cframe * c0).Position(), -(part0.lock()->cframe * c0).LookVector().Unit());
this->joint = dynamic_cast<rp::HingeJoint*>(workspace->physicsWorld->createJoint(jointInfo));
this->joint = dynamic_cast<rp::HingeJoint*>(workspace->CreateJoint(jointInfo));
jointWorkspace = workspace;
// part1.lock()->rigidBody->getCollider(0)->setCollideWithMaskBits(0b10);
@ -41,8 +40,8 @@ void Rotate::buildJoint() {
// !!! REMINDER: This has to be called manually when parts are destroyed/removed from the workspace, or joints will linger
void Rotate::breakJoint() {
// If the joint doesn't exist, or its workspace expired (not our problem anymore), then no need to do anything
if (!this->joint || jointWorkspace.expired() || !jointWorkspace.lock()->physicsWorld) return;
if (!this->joint || jointWorkspace.expired()) return;
jointWorkspace.lock()->physicsWorld->destroyJoint(this->joint);
jointWorkspace.lock()->DestroyJoint(this->joint);
this->joint = nullptr;
}

View file

@ -22,7 +22,6 @@ void RotateV::buildJoint() {
if ((!GetParent() || GetParent().value()->GetClass() != &JointsService::TYPE) && !workspace()) return;
std::shared_ptr<Workspace> workspace = workspaceOfPart(part0.lock()).value();
if (!workspace->physicsWorld) return;
// Update Part1's rotation and cframe prior to creating the joint as reactphysics3d locks rotation based on how it
@ -35,7 +34,7 @@ void RotateV::buildJoint() {
jointInfo.isCollisionEnabled = false;
this->joint = dynamic_cast<rp::HingeJoint*>(workspace->physicsWorld->createJoint(jointInfo));
this->joint = dynamic_cast<rp::HingeJoint*>(workspace->CreateJoint(jointInfo));
jointWorkspace = workspace;
@ -47,8 +46,8 @@ void RotateV::buildJoint() {
void RotateV::breakJoint() {
// If the joint doesn't exist, or its workspace expired (not our problem anymore), then no need to do anything
if (!this->joint || jointWorkspace.expired() || !jointWorkspace.lock()->physicsWorld) return;
if (!this->joint || jointWorkspace.expired()) return;
jointWorkspace.lock()->physicsWorld->destroyJoint(this->joint);
jointWorkspace.lock()->DestroyJoint(this->joint);
this->joint = nullptr;
}

View file

@ -24,7 +24,6 @@ void Snap::buildJoint() {
if ((!GetParent() || GetParent().value()->GetClass() != &JointsService::TYPE) && !workspace()) return;
std::shared_ptr<Workspace> workspace = workspaceOfPart(part0.lock()).value();
if (!workspace->physicsWorld) return;
// Update Part1's rotation and cframe prior to creating the joint as reactphysics3d locks rotation based on how it
// used to be rather than specifying an anchor rotation, so whatever.
@ -33,15 +32,15 @@ void Snap::buildJoint() {
workspace->SyncPartPhysics(part1.lock());
rp::FixedJointInfo jointInfo(part0.lock()->rigidBody, part1.lock()->rigidBody, (c0.Inverse() * c1).Position());
this->joint = dynamic_cast<rp::FixedJoint*>(workspace->physicsWorld->createJoint(jointInfo));
this->joint = dynamic_cast<rp::FixedJoint*>(workspace->CreateJoint(jointInfo));
jointWorkspace = workspace;
}
// !!! REMINDER: This has to be called manually when parts are destroyed/removed from the workspace, or joints will linger
void Snap::breakJoint() {
// If the joint doesn't exist, or its workspace expired (not our problem anymore), then no need to do anything
if (!this->joint || jointWorkspace.expired() || !jointWorkspace.lock()->physicsWorld) return;
if (!this->joint || jointWorkspace.expired()) return;
jointWorkspace.lock()->physicsWorld->destroyJoint(this->joint);
jointWorkspace.lock()->DestroyJoint(this->joint);
this->joint = nullptr;
}

View file

@ -24,7 +24,6 @@ void Weld::buildJoint() {
if ((!GetParent() || GetParent().value()->GetClass() != &JointsService::TYPE) && !workspace()) return;
std::shared_ptr<Workspace> workspace = workspaceOfPart(part0.lock()).value();
if (!workspace->physicsWorld) return;
// Update Part1's rotation and cframe prior to creating the joint as reactphysics3d locks rotation based on how it
// used to be rather than specifying an anchor rotation, so whatever.
@ -33,15 +32,15 @@ void Weld::buildJoint() {
workspace->SyncPartPhysics(part1.lock());
rp::FixedJointInfo jointInfo(part0.lock()->rigidBody, part1.lock()->rigidBody, (c0.Inverse() * c1).Position());
this->joint = dynamic_cast<rp::FixedJoint*>(workspace->physicsWorld->createJoint(jointInfo));
this->joint = dynamic_cast<rp::FixedJoint*>(workspace->CreateJoint(jointInfo));
jointWorkspace = workspace;
}
// !!! REMINDER: This has to be called manually when parts are destroyed/removed from the workspace, or joints will linger
void Weld::breakJoint() {
// If the joint doesn't exist, or its workspace expired (not our problem anymore), then no need to do anything
if (!this->joint || jointWorkspace.expired() || !jointWorkspace.lock()->physicsWorld) return;
if (!this->joint || jointWorkspace.expired()) return;
jointWorkspace.lock()->physicsWorld->destroyJoint(this->joint);
jointWorkspace.lock()->DestroyJoint(this->joint);
this->joint = nullptr;
}

View file

@ -49,6 +49,15 @@ void Part::OnAncestryChanged(std::optional<std::shared_ptr<Instance>> child, std
// TODO: Sleeping bodies that touch this one also need to be updated
}
void Part::OnWorkspaceAdded(std::optional<std::shared_ptr<Workspace>> oldWorkspace, std::shared_ptr<Workspace> newWorkspace) {
newWorkspace->AddBody(shared<Part>());
}
void Part::OnWorkspaceRemoved(std::shared_ptr<Workspace> oldWorkspace) {
if (simulationTicket->get() != nullptr)
oldWorkspace->RemoveBody(shared<Part>());
}
void Part::onUpdated(std::string property) {
// Reset velocity
if (property != "Velocity")

View file

@ -1,5 +1,6 @@
#pragma once
#include <list>
#include <memory>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
@ -9,6 +10,7 @@
#include "datatypes/vector.h"
#include "objects/base/instance.h"
#include "enum/surface.h"
#include <mutex>
#include <optional>
#include <reactphysics3d/reactphysics3d.h>
#include <vector>
@ -30,6 +32,12 @@ struct PartConstructParams {
class Workspace;
#ifndef __SIMULATION_TICKET
#define __SIMULATION_TICKET
class Part;
typedef std::list<std::shared_ptr<Part>>::iterator SimulationTicket;
#endif
class DEF_INST_(explorer_icon="part") Part : public PVInstance {
AUTOGEN_PREAMBLE
protected:
@ -50,6 +58,8 @@ protected:
friend JointInstance;
friend Workspace;
virtual void OnWorkspaceAdded(std::optional<std::shared_ptr<Workspace>> oldWorkspace, std::shared_ptr<Workspace> newWorkspace) override;
virtual void OnWorkspaceRemoved(std::shared_ptr<Workspace> oldWorkspace) override;
void OnAncestryChanged(std::optional<std::shared_ptr<Instance>> child, std::optional<std::shared_ptr<Instance>> newParent) override;
void onUpdated(std::string);
public:
@ -99,6 +109,8 @@ public:
DEF_SIGNAL SignalSource TouchEnded;
rp::RigidBody* rigidBody = nullptr;
SimulationTicket simulationTicket;
bool rigidBodyDirty = true;
inline SurfaceType GetSurfaceFromFace(NormalId face) { return surfaceFromFace(face); }
float GetSurfaceParamA(Vector3 face);

View file

@ -93,8 +93,11 @@ void ScriptContext::PushThreadSleep(lua_State* thread, float delay) {
lua_pop(state, 1); // pop sleepingThreads
}
tu_time_t schedTime;
void ScriptContext::RunSleepingThreads() {
for (size_t i = 0; i < sleepingThreads.size();) {
tu_time_t startTime = tu_clock_micros();
size_t i;
for (i = 0; i < sleepingThreads.size();) {
bool deleted = false;
SleepingThread sleep = sleepingThreads[i];
@ -127,6 +130,8 @@ void ScriptContext::RunSleepingThreads() {
if (!deleted)
i++;
}
if (i > 0)
schedTime = tu_clock_micros() - startTime;
}
std::string ScriptContext::RegisterScriptSource(std::shared_ptr<Script> script) {

View file

@ -2,11 +2,14 @@
#include "datatypes/variant.h"
#include "datatypes/ref.h"
#include "datatypes/vector.h"
#include "logger.h"
#include "objects/base/instance.h"
#include "objects/part.h"
#include "objects/service/jointsservice.h"
#include "objects/joint/jointinstance.h"
#include "objects/datamodel.h"
#include "physics/util.h"
#include "timeutil.h"
#include <memory>
#include <reactphysics3d/collision/CollisionCallback.h>
#include <reactphysics3d/collision/OverlapCallback.h>
@ -15,10 +18,11 @@
rp::PhysicsCommon* Workspace::physicsCommon = new rp::PhysicsCommon;
Workspace::Workspace(): Service(&TYPE), physicsEventListener(this) {
physicsWorld = physicsCommon->createPhysicsWorld();
}
Workspace::~Workspace() {
if (physicsWorld && physicsCommon)
if (physicsCommon)
physicsCommon->destroyPhysicsWorld(physicsWorld);
}
@ -66,8 +70,6 @@ void Workspace::InitService() {
if (initialized) return;
initialized = true;
physicsWorld = physicsCommon->createPhysicsWorld();
physicsWorld->setGravity(rp::Vector3(0, -196.2, 0));
// world->setContactsPositionCorrectionTechnique(rp3d::ContactsPositionCorrectionTechnique::BAUMGARTE_CONTACTS);
physicsWorld->setNbIterationsPositionSolver(2000);
@ -82,7 +84,6 @@ void Workspace::InitService() {
std::shared_ptr<Instance> obj = *it;
if (!obj->IsA<Part>()) continue;
std::shared_ptr<Part> part = obj->CastTo<Part>().expect();
this->SyncPartPhysics(part);
part->MakeJoints();
}
@ -101,9 +102,7 @@ void Workspace::InitService() {
}
}
void Workspace::SyncPartPhysics(std::shared_ptr<Part> part) {
if (!physicsWorld) return;
void Workspace::updatePartPhysics(std::shared_ptr<Part> part) {
rp::Transform transform = part->cframe;
if (!part->rigidBody) {
part->rigidBody = physicsWorld->createRigidBody(transform);
@ -144,15 +143,45 @@ void Workspace::SyncPartPhysics(std::shared_ptr<Part> part) {
part->rigidBody->setUserData(&*part);
}
void Workspace::SyncPartPhysics(std::shared_ptr<Part> part) {
if (globalPhysicsLock.try_lock()) {
updatePartPhysics(part);
globalPhysicsLock.unlock();
} else {
part->rigidBodyDirty = true;
}
}
tu_time_t physTime;
void Workspace::PhysicsStep(float deltaTime) {
// Step the simulation a few steps
tu_time_t startTime = tu_clock_micros();
std::scoped_lock lock(globalPhysicsLock);
physicsWorld->update(std::min(deltaTime / 2, (1/60.f)));
// Update queued objects
queueLock.lock();
for (QueueItem item : bodyQueue) {
if (item.action == QueueItem::QUEUEITEM_ADD) {
simulatedBodies.push_back(item.part);
item.part->simulationTicket = --simulatedBodies.end();
} else if (item.part->simulationTicket->get() != nullptr) {
simulatedBodies.erase(item.part->simulationTicket);
item.part->simulationTicket = {};
}
}
queueLock.unlock();
// TODO: Add list of tracked parts in workspace based on their ancestry using inWorkspace property of Instance
for (auto it = this->GetDescendantsStart(); it != this->GetDescendantsEnd(); it++) {
std::shared_ptr<Instance> obj = *it;
if (!obj->IsA<Part>()) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(obj);
for (std::shared_ptr<Part> part : simulatedBodies) {
// If the part's body is dirty, update it now instead
if (part->rigidBodyDirty) {
updatePartPhysics(part);
part->rigidBodyDirty = false;
continue;
}
if (!part->rigidBody) continue;
// Sync properties
const rp::Transform& transform = part->rigidBody->getTransform();
@ -180,6 +209,8 @@ void Workspace::PhysicsStep(float deltaTime) {
parent.value()->Destroy();
}
}
physTime = tu_clock_micros() - startTime;
}
@ -231,6 +262,7 @@ public:
};
std::optional<const RaycastResult> Workspace::CastRayNearest(glm::vec3 point, glm::vec3 rotation, float maxLength, std::optional<RaycastFilter> filter, unsigned short categoryMaskBits) {
// std::scoped_lock lock(globalPhysicsLock);
rp::Ray ray(glmToRp(point), glmToRp(glm::normalize(rotation)) * maxLength);
NearestRayHit rayHit(glmToRp(point), filter);
physicsWorld->raycast(ray, &rayHit, categoryMaskBits);
@ -238,5 +270,31 @@ std::optional<const RaycastResult> Workspace::CastRayNearest(glm::vec3 point, gl
}
void Workspace::DestroyRigidBody(rp::RigidBody* rigidBody) {
std::scoped_lock lock(globalPhysicsLock);
physicsWorld->destroyRigidBody(rigidBody);
}
void Workspace::DestroyJoint(rp::Joint* joint) {
std::scoped_lock lock(globalPhysicsLock);
physicsWorld->destroyJoint(joint);
}
rp::Joint* Workspace::CreateJoint(const rp::JointInfo& jointInfo) {
std::scoped_lock lock(globalPhysicsLock);
rp::Joint* joint = physicsWorld->createJoint(jointInfo);
return joint;
}
void Workspace::AddBody(std::shared_ptr<Part> part) {
queueLock.lock();
bodyQueue.push_back({part, QueueItem::QUEUEITEM_ADD});
part->rigidBodyDirty = true;
queueLock.unlock();
}
void Workspace::RemoveBody(std::shared_ptr<Part> part) {
queueLock.lock();
bodyQueue.push_back({part, QueueItem::QUEUEITEM_REMOVE});
queueLock.unlock();
}

View file

@ -2,8 +2,11 @@
#include "objects/annotation.h"
#include "objects/base/service.h"
#include "utils.h"
#include <glm/ext/vector_float3.hpp>
#include <list>
#include <memory>
#include <mutex>
#include <reactphysics3d/body/RigidBody.h>
#include <reactphysics3d/engine/EventListener.h>
#include <reactphysics3d/engine/PhysicsCommon.h>
@ -34,8 +37,21 @@ class Weld;
class Rotate;
class RotateV;
#ifndef __SIMULATION_TICKET
#define __SIMULATION_TICKET
typedef std::list<std::shared_ptr<Part>>::iterator SimulationTicket;
#endif
typedef std::function<FilterResult(std::shared_ptr<Part>)> RaycastFilter;
struct QueueItem {
std::shared_ptr<Part> part;
enum {
QUEUEITEM_ADD,
QUEUEITEM_REMOVE,
} action;
};
class Workspace;
class PhysicsEventListener : public rp::EventListener {
friend Workspace;
@ -50,15 +66,13 @@ class PhysicsEventListener : public rp::EventListener {
class DEF_INST_SERVICE_(explorer_icon="workspace") Workspace : public Service {
AUTOGEN_PREAMBLE
rp::PhysicsWorld* physicsWorld = nullptr;
std::list<std::shared_ptr<Part>> simulatedBodies;
std::list<QueueItem> bodyQueue;
rp::PhysicsWorld* physicsWorld;
static rp::PhysicsCommon* physicsCommon;
PhysicsEventListener physicsEventListener;
friend Part;
friend Snap;
friend Weld;
friend Rotate;
friend RotateV;
void updatePartPhysics(std::shared_ptr<Part> part);
protected:
void InitService() override;
bool initialized = false;
@ -67,13 +81,21 @@ public:
Workspace();
~Workspace();
std::mutex globalPhysicsLock;
std::recursive_mutex queueLock;
DEF_PROP float fallenPartsDestroyHeight = -500;
// static inline std::shared_ptr<Workspace> New() { return std::make_shared<Workspace>(); };
static inline std::shared_ptr<Instance> Create() { return std::make_shared<Workspace>(); };
void SyncPartPhysics(std::shared_ptr<Part> part);
void AddBody(std::shared_ptr<Part> part);
void RemoveBody(std::shared_ptr<Part> part);
void DestroyRigidBody(rp::RigidBody* rigidBody);
void SyncPartPhysics(std::shared_ptr<Part> part);
rp::Joint* CreateJoint(const rp::JointInfo& jointInfo);
void DestroyJoint(rp::Joint* joint);
void PhysicsStep(float deltaTime);
std::optional<const RaycastResult> CastRayNearest(glm::vec3 point, glm::vec3 rotation, float maxLength, std::optional<RaycastFilter> filter = std::nullopt, unsigned short categoryMaskBits = 0xFFFF);

View file

@ -94,7 +94,7 @@ void PartAssembly::Scale(Vector3 newSize, bool scaleUp) {
parts[0]->size = newSize;
parts[0]->UpdateProperty("Size");
sendPropertyUpdatedSignal(parts[0], "Size", Variant(parts[0]->size));
_bounds = newSize;
_size = _bounds = newSize;
return;
}
@ -116,7 +116,7 @@ void PartAssembly::Scale(Vector3 newSize, bool scaleUp) {
sendPropertyUpdatedSignal(part, "Size", Variant(part->size));
}
_bounds = _bounds * factor;
_size = _bounds = _bounds * factor;
}
std::vector<PartTransformState> PartAssembly::GetCurrentTransforms() {

View file

@ -0,0 +1,90 @@
#include "rendering/shader.h"
#include "rendering/texture3d.h"
#include "timeutil.h"
#include <GL/glew.h>
#include <GL/gl.h>
#include <glm/ext/vector_float4.hpp>
#include <string>
extern int viewportWidth, viewportHeight;
extern Texture3D* fontTexture;
extern Shader* fontShader;
extern Shader* identityShader;
void drawChar(char c, int x, int y, float scale=1.f) {
fontShader->use();
fontTexture->activate(1);
fontShader->set("fontTex", 1);
fontShader->set("charIndex", (int)c);
// https://stackoverflow.com/a/10631263
int tex = fontShader->getAttribute("aTexCoord");
y = viewportHeight - y - 16*scale;
float x0 = float(x)/viewportWidth, y0 = float(y)/viewportHeight, x1 = ((float)x + 8*scale)/viewportWidth, y1 = ((float)y + 16*scale)/viewportHeight;
x0 *= 2, y0 *= 2, x1 *= 2, y1 *= 2;
x0 -= 1, y0 -= 1, x1 -= 1, y1 -= 1;
glBegin(GL_QUADS);
glVertex3f(x0, y0, 0); glVertexAttrib2f(tex, 1, 1);
glVertex3f(x1, y0, 0); glVertexAttrib2f(tex, 1, 0);
glVertex3f(x1, y1, 0); glVertexAttrib2f(tex, 0, 0);
glVertex3f(x0, y1, 0); glVertexAttrib2f(tex, 0, 1);
glEnd();
}
void drawString(std::string str, int x, int y, float scale=1.f) {
for (int i = 0; i < (int)str.length(); i++) {
char c = str[i];
drawChar(c, x+i*8*scale, y, scale);
}
}
void drawRect(int x, int y, int w, int h, glm::vec4 color) {
identityShader->use();
identityShader->set("aColor", color);
float x0 = 2*float(x)/viewportWidth-1, y0 = 2*float(y)/viewportHeight-1, x1 = 2*float(x + w)/viewportWidth-1, y1 = 2*float(y + h)/viewportHeight-1;
float tmp;
tmp = -y0, y0 = -y1, y1 = tmp;
glBegin(GL_QUADS);
glVertex3f(x0, y0, 0);
glVertex3f(x1, y0, 0);
glVertex3f(x1, y1, 0);
glVertex3f(x0, y1, 0);
glEnd();
}
static tu_time_t lastTime;
extern tu_time_t renderTime;
extern tu_time_t physTime;
extern tu_time_t schedTime;
// Draws debug info window
// Including info about framerates, etc.
void renderDebugInfo() {
tu_time_t timePassed = tu_clock_micros() - lastTime;
float frames = 1/(((float)timePassed)/1'000'000);
glDisable(GL_DEPTH_TEST);
drawRect(0, 0, 200, 16*8, glm::vec4(0.2f,0.2f,0.2f,0.8f));
drawString("FPS: " + std::to_string((int)frames), 0, 16*0);
drawString(" 1/: " + std::to_string((float)timePassed/1'000'000), 0, 16*1);
frames = 1/(((float)renderTime)/1'000'000);
drawString("RPS: " + std::to_string((int)frames), 0, 16*2);
drawString(" 1/: " + std::to_string((float)renderTime/1'000'000), 0, 16*3);
frames = 1/(((float)physTime)/1'000'000);
drawString("PPS: " + std::to_string((int)frames), 0, 16*4);
drawString(" 1/: " + std::to_string((float)physTime/1'000'000), 0, 16*5);
frames = 1/(((float)schedTime)/1'000'000);
drawString("SPS: " + std::to_string((int)frames), 0, 16*6);
drawString(" 1/: " + std::to_string((float)schedTime/1'000'000), 0, 16*7);
lastTime = tu_clock_micros();
}

View file

@ -21,6 +21,7 @@
#include "math_helper.h"
#include "objects/service/selection.h"
#include "partassembly.h"
#include "rendering/texture.h"
#include "rendering/torus.h"
#include "shader.h"
#include "mesh.h"
@ -31,6 +32,7 @@
#include "skybox.h"
#include "enum/surface.h"
#include "texture3d.h"
#include "timeutil.h"
#include "renderer.h"
@ -41,13 +43,18 @@ Shader* identityShader = NULL;
Shader* ghostShader = NULL;
Shader* wireframeShader = NULL;
Shader* outlineShader = NULL;
Shader* fontShader = NULL;
extern Camera camera;
Skybox* skyboxTexture = NULL;
Texture3D* studsTexture = NULL;
Texture* fontTexture = NULL;
bool debugRendererEnabled = false;
bool wireframeRendering = false;
static int viewportWidth, viewportHeight;
int viewportWidth, viewportHeight;
void renderDebugInfo();
void renderInit(GLFWwindow* window, int width, int height) {
viewportWidth = width, viewportHeight = height;
@ -60,6 +67,8 @@ void renderInit(GLFWwindow* window, int width, int height) {
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
fontTexture = new Texture("assets/textures/debugfnt.bmp", GL_RGB);
skyboxTexture = new Skybox({
"assets/textures/skybox/null_plainsky512_lf.jpg",
"assets/textures/skybox/null_plainsky512_rt.jpg",
@ -79,6 +88,7 @@ void renderInit(GLFWwindow* window, int width, int height) {
ghostShader = new Shader("assets/shaders/ghost.vs", "assets/shaders/ghost.fs");
wireframeShader = new Shader("assets/shaders/wireframe.vs", "assets/shaders/wireframe.fs");
outlineShader = new Shader("assets/shaders/outline.vs", "assets/shaders/outline.fs");
fontShader = new Shader("assets/shaders/font.vs", "assets/shaders/font.fs");
}
void renderParts() {
@ -322,7 +332,7 @@ void renderHandles() {
glDisable(GL_CULL_FACE);
identityShader->use();
identityShader->set("aColor", glm::vec3(0.f, 1.f, 1.f));
identityShader->set("aColor", glm::vec4(0.f, 1.f, 1.f, 1.f));
for (auto face : HandleFace::Faces) {
CFrame cframe = getHandleCFrame(face);
@ -625,9 +635,12 @@ void addDebugRenderCFrame(CFrame frame, Color3 color) {
DEBUG_CFRAMES.push_back(std::make_pair(frame, color));
}
tu_time_t renderTime;
void render(GLFWwindow* window) {
tu_time_t startTime = tu_clock_micros();
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
renderSkyBox();
renderHandles();
@ -639,10 +652,17 @@ void render(GLFWwindow* window) {
renderRotationArcs();
if (wireframeRendering)
renderWireframe();
if (debugRendererEnabled)
renderDebugInfo();
// TODO: Make this a debug flag
// renderAABB();
renderTime = tu_clock_micros() - startTime;
}
void setViewport(int width, int height) {
viewportWidth = width, viewportHeight = height;
}
void setDebugRendererEnabled(bool enabled) {
debugRendererEnabled = enabled;
}

View file

@ -3,10 +3,12 @@
extern bool wireframeRendering;
namespace Data { class CFrame; class Color3; };
class CFrame;
class Color3;
void renderInit(GLFWwindow* window, int width, int height);
void render(GLFWwindow* window);
void setViewport(int width, int height);
void addDebugRenderCFrame(CFrame);
void addDebugRenderCFrame(CFrame, Color3);
void addDebugRenderCFrame(CFrame, Color3);
void setDebugRendererEnabled(bool enabled);

View file

@ -100,10 +100,18 @@ void Shader::set(std::string key, glm::vec3 value) {
glUniform3f(glGetUniformLocation(id, key.c_str()), value.x, value.y, value.z);
}
void Shader::set(std::string key, glm::vec4 value) {
glUniform4f(glGetUniformLocation(id, key.c_str()), value.x, value.y, value.z, value.w);
}
void Shader::set(std::string key, glm::mat3 value) {
glUniformMatrix3fv(glGetUniformLocation(id, key.c_str()), 1, GL_FALSE, glm::value_ptr(value));
}
void Shader::set(std::string key, glm::mat4 value) {
glUniformMatrix4fv(glGetUniformLocation(id, key.c_str()), 1, GL_FALSE, glm::value_ptr(value));
}
}
int Shader::getAttribute(std::string key) {
return glGetAttribLocation(id, key.c_str());
}

View file

@ -19,6 +19,9 @@ public:
void set(std::string key, DirLight value);
void set(std::string key, PointLight value);
void set(std::string key, glm::vec3 value);
void set(std::string key, glm::vec4 value);
void set(std::string key, glm::mat3 value);
void set(std::string key, glm::mat4 value);
int getAttribute(std::string key);
};

View file

@ -1,9 +1,12 @@
#pragma once
#ifdef __clang__
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wnullability-extension"
#define nullable _Nullable
#define notnull _Nonnull
#elif defined(__GNUC__)
#define nullable
#define notnull __attribute__((nonnull))
#else
#define nullable
#define notnull

View file

@ -226,6 +226,7 @@ void MainGLWidget::handleLinearTransform(QMouseEvent* evt) {
if (editorToolHandles.handlesType == MoveHandles) {
selectionAssembly.TransformBy(CFrame() + absDiff);
} else if (editorToolHandles.handlesType == ScaleHandles) {
Vector3 oldSize = selectionAssembly.size();
if (evt->modifiers() & Qt::AltModifier) {
// If size gets too small, don't
if (glm::any(glm::lessThan(glm::vec3(selectionAssembly.size() + abs(draggingHandle->normal) * diff * 2.f), glm::vec3(0.001f))))
@ -240,6 +241,9 @@ void MainGLWidget::handleLinearTransform(QMouseEvent* evt) {
selectionAssembly.TransformBy(CFrame() + absDiff * 0.5f);
selectionAssembly.Scale(selectionAssembly.size() + abs(draggingHandle->normal) * diff, diff > 0);
}
if (snappingFactor() > 0 && oldSize != selectionAssembly.size() && mainWindow()->editSoundEffects && QFile::exists("./assets/excluded/switch.wav"))
playSound("./assets/excluded/switch.wav");
}
}
@ -524,6 +528,12 @@ void MainGLWidget::keyPressEvent(QKeyEvent* evt) {
lastPart->name = "Part" + std::to_string(partId++);
M_mainWindow->undoManager.PushState({ UndoStateInstanceCreated { lastPart, gWorkspace() } });
}
if (evt->key() == Qt::Key_BracketLeft) {
static bool debugRenderEnabled;
debugRenderEnabled = !debugRenderEnabled;
setDebugRendererEnabled(debugRenderEnabled);
}
}
void MainGLWidget::keyReleaseEvent(QKeyEvent* evt) {

View file

@ -6,7 +6,7 @@
<rect>
<x>0</x>
<y>0</y>
<width>1027</width>
<width>1050</width>
<height>750</height>
</rect>
</property>

View file

@ -3,21 +3,55 @@
#include "datatypes/variant.h"
#include "mainglwidget.h"
#include "mainwindow.h"
#include "objects/joint/snap.h"
#include "objects/script.h"
#include "objects/service/script/scriptcontext.h"
#include "enum/surface.h"
#include <cstdio>
#include <chrono>
#include <memory>
#include <mutex>
#include <qboxlayout.h>
#include <qcoreevent.h>
#include <qdebug.h>
#include <qevent.h>
#include <qglobal.h>
#include <qmargins.h>
#include <qmdisubwindow.h>
#include <qlayout.h>
#include <qmimedata.h>
#include <qmutex.h>
#include <qwaitcondition.h>
#include <thread>
#include "../ui_mainwindow.h"
#include "objects/service/selection.h"
#include "timeutil.h"
class PlaceDocumentPhysicsWorker {
public:
std::mutex sync;
std::thread thread;
std::condition_variable runningCond;
bool running = false;
bool quit = false;
PlaceDocumentPhysicsWorker() : thread(&PlaceDocumentPhysicsWorker::doWork, this) {}
private:
tu_time_t lastTime = tu_clock_micros();
void doWork() {
do {
tu_time_t deltaTime = tu_clock_micros() - lastTime;
lastTime = tu_clock_micros();
// First frame is always empty
if (deltaTime > 100) {
gWorkspace()->PhysicsStep(float(deltaTime)/1'000'000);
}
std::this_thread::sleep_for(std::chrono::microseconds(16'667 - deltaTime));
std::unique_lock lock(sync);
runningCond.wait(lock, [&]{ return running || quit; });
lock.unlock();
} while (!quit);
}
};
PlaceDocument::PlaceDocument(QWidget* parent):
QMdiSubWindow(parent) {
@ -28,15 +62,29 @@ PlaceDocument::PlaceDocument(QWidget* parent):
_runState = RUN_STOPPED;
updateSelectionListeners(gDataModel->GetService<Selection>());
worker = new PlaceDocumentPhysicsWorker();
}
PlaceDocument::~PlaceDocument() {
worker->quit = true;
worker->runningCond.notify_all();
worker->thread.join();
}
void PlaceDocument::updatePhysicsWorker() {
{
std::lock_guard lock(worker->sync);
worker->running = _runState == RUN_RUNNING;
}
worker->runningCond.notify_all();
}
void PlaceDocument::setRunState(RunState newState) {
if (newState == RUN_RUNNING && _runState != RUN_RUNNING) {
if (_runState == RUN_PAUSED) {
_runState = RUN_RUNNING;
updatePhysicsWorker();
return;
}
@ -55,6 +103,8 @@ void PlaceDocument::setRunState(RunState newState) {
gDataModel = editModeDataModel;
updateSelectionListeners(gDataModel->GetService<Selection>());
}
updatePhysicsWorker();
}
void PlaceDocument::updateSelectionListeners(std::shared_ptr<Selection> selection) {
@ -81,18 +131,12 @@ void PlaceDocument::closeEvent(QCloseEvent *closeEvent) {
}
std::shared_ptr<Part> shit;
static std::chrono::time_point lastTime = std::chrono::steady_clock::now();
void PlaceDocument::timerEvent(QTimerEvent* evt) {
if (evt->timerId() != timer.timerId()) {
QWidget::timerEvent(evt);
return;
}
float deltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(std::chrono::steady_clock::now() - lastTime).count();
lastTime = std::chrono::steady_clock::now();
if (_runState == RUN_RUNNING)
gWorkspace()->PhysicsStep(deltaTime);
placeWidget->repaint();
placeWidget->updateCycle();
gDataModel->GetService<ScriptContext>()->RunSleepingThreads();

View file

@ -2,11 +2,18 @@
#include "datatypes/signal.h"
#include "mainglwidget.h"
#include <condition_variable>
#include <mutex>
#include <qevent.h>
#include <qmdisubwindow.h>
#include <qthread.h>
#include <qmutex.h>
#include <qwaitcondition.h>
#include <QBasicTimer>
#include <type_traits>
class Selection;
class PlaceDocumentPhysicsWorker;
enum RunState {
RUN_STOPPED,
@ -18,10 +25,14 @@ class PlaceDocument : public QMdiSubWindow {
QBasicTimer timer;
RunState _runState;
PlaceDocumentPhysicsWorker* worker;
std::weak_ptr<SignalConnection> selectionConnection;
void timerEvent(QTimerEvent*) override;
void updateSelectionListeners(std::shared_ptr<Selection>);
void updatePhysicsWorker();
public:
MainGLWidget* placeWidget;
PlaceDocument(QWidget* parent = nullptr);

View file

@ -7,7 +7,7 @@ void UndoHistory::PushState(UndoState state) {
redoHistory = {};
if (maxBufferSize != -1 && (int)undoHistory.size() > maxBufferSize)
undoHistory.erase(undoHistory.begin(), undoHistory.begin()+maxBufferSize-(int)undoHistory.size()-1);
undoHistory.pop_front();
undoHistory.push_back(state);
undoStateListener();