Giter Club home page Giter Club logo

threepp's Introduction

threepp (Work in progress)

Cross-platform C++17 port of the popular Javascript 3D library three.js r129.

Current state of the project

Most of the core library has been ported, including advanced rendering capabilities, however much remains to be done..

What works?
  • Line, Points, Mesh, InstancedMesh
  • Geometries [Box, Sphere, Plane, Cylindrical, Capsule, Tube, ++]
  • Lights [Ambient, Directional, Point, Spot, Hemi]
  • Raycasting [Mesh, Line, Points]
  • 2D/3D Textures, 3D text, Sprites, RenderTarget, CubeMaps
  • Transparency, Shadows
  • Morphtargets, Bones
  • Controls [Orbit, Fly, Drag]
  • Water and Sky shaders
  • Built-in text rendering and font loading [typeface.json, TTF]
  • Loaders [Binary STL, OBJ/MTL, SVG]
  • Basic Audio support using miniaudio
  • Generic model loader based on Assimp
  • Easy integration with Dear ImGui

Builds on Windows, Linux, MacOS, MinGW and with Emscripten.

But, but why?

Because fun.

How to build

threepp comes bundled with all required core dependencies.

Use CMake for project configuration and building.

Windows
cmake . -A x64 -B build -DCMAKE_BUILD_TYPE="Release"
cmake --build build --config "Release"
Unix
cmake . -B build -DCMAKE_BUILD_TYPE="Release"
cmake --build build

However, some of the examples (and headers) require additional dependencies. To make use of all features and to enable/build all examples, the use of vcpkg is encouraged.

vcpkg (using manifest mode)

Call CMake with -DCMAKE_TOOLCHAIN_FILE=[path to vcpkg]/scripts/buildsystems/vcpkg.cmake

Add optional features by listing them with -DVCPKG_MANIFEST_FEATURES=feature1;feature2

See vcpkg.json for available features.

Note, however, that under MinGW you'll need to specify the vcpkg triplet:

-DVCPKG_TARGET_TRIPLET=x64-mingw-[static|dynamic]  # choose either `static` or `dynamic`.
-DVCPKG_HOST_TRIPLET=x64-mingw-[static|dynamic]    # <-- needed only if MSVC cannot be found. 
Building examples with Emscripten

Pass to CMake:

-DCMAKE_TOOLCHAIN_FILE="[path to emscripten]\emsdk\upstream\emscripten\cmake\Modules\Platform\Emscripten.cmake"

When using vcpkg, however, do:

-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="[path to emscripten]\emsdk\upstream\emscripten\cmake\Modules\Platform\Emscripten.cmake"

This will generate .html versions of a subset of the examples to be loaded in a browser.

Optional downstream dependencies

When consuming threepp in your own application, some headers will require additional dependencies in order to compile.

Header Dependency Description
AssimpLoader assimp Import a wide variety of different 3D formats
ImguiContext imgui ImGUI utility

Implementation notes

In general, you'll find that math classes are value types, while threepp expect smart pointers for other types. For convenience, geometries, materials etc. has a static ::create function that returns a std::shared_ptr. Thus, you don't necessarily need to handle memory explicitly using threepp. Furthermore, materials, geometries and textures are automatically disposed when they go out of scope. Yay!

Example

#include "threepp/threepp.hpp"

using namespace threepp;

auto createBox(const Vector3& pos, const Color& color) {
    auto geometry = BoxGeometry::create();
    auto material = MeshPhongMaterial::create();
    material->color = color;
    
    auto box = Mesh::create(geometry, material);
    box->position.copy(pos);
    
    return box;
}

auto createPlane() {
    auto planeGeometry = PlaneGeometry::create(5, 5);
    auto planeMaterial = MeshLambertMaterial::create();
    planeMaterial->color = Color::gray;
    planeMaterial->side = Side::Double;
    
    auto plane = Mesh::create(planeGeometry, planeMaterial);
    plane->position.y = -1;
    plane->rotateX(math::degToRad(90));
    
    return plane;
}

int main() {

    Canvas canvas("Demo");
    GLRenderer renderer{canvas.size()};

    auto scene = Scene::create();
    auto camera = PerspectiveCamera::create(75, canvas.aspect(), 0.1f, 100);
    camera->position.z = 5;
    
    OrbitControls controls{*camera, canvas};

    auto light = HemisphereLight::create();
    scene->add(light);

    auto plane = createPlane();
    scene->add(plane);
    
    auto group = Group::create();
    group->add(createBox({-1, 0, 0}, Color::green));
    group->add(createBox({1, 0, 0}, Color::red));
    scene->add(group);

    canvas.onWindowResize([&](WindowSize size) {
        camera->aspect = size.aspect();
        camera->updateProjectionMatrix();
        renderer.setSize(size);
    });
    
    Clock clock;
    canvas.animate([&]() {
        
        float dt = clock.getDelta();
        group->rotation.y += 1.f * dt;

        renderer.render(*scene, *camera);
    });
}

Consuming threepp

Threepp is available as a CMake package and can be consumed in a number of ways.

CMake FetchContent (recommended)

threepp is compatible with CMake's FetchContent:

include(FetchContent)
set(THREEPP_BUILD_TESTS OFF)
set(THREEPP_BUILD_EXAMPLES OFF)
FetchContent_Declare(
        threepp
        GIT_REPOSITORY https://github.com/markaren/threepp.git
        GIT_TAG tag_or_commit_hash
)
FetchContent_MakeAvailable(threepp)
#...
target_link_libraries(main PUBLIC threepp::threepp)

This is the preferred approach, as it enables users to update the targeted threepp version at will.

An example is provided here. See also this demo, which additionally uses WxWidgets as the Window system.

vcpkg

threepp is available for use with vcpkg through a custom vcpkg-registry. However, this vcpkg port is cumbersome to maintain and is not so often updated, and support may be discontinued in the future.

An example is provided here.

Screenshots

Fonts LeePerrySmith Shadows FlyControls Crane Optimization Physics Water MotorController

threepp's People

Contributors

daniellinpioneer avatar josefgraus avatar maidamai0 avatar makeclean avatar markaren avatar robbiefish avatar salamaashoush avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

threepp's Issues

CubeMap texture support

I want to add a cubemap texture function and implement the envMap feature in GLBackground.cpp. I tried adding CubeTexture and CubeTextureLoader and wrote a shader code to verify. I used RenderDoc to see that the cubemap texture was loaded correctly, but I still can't see the result. I've been trying for a week, and I think I'm very close. I can provide the code I wrote, can you help me identify the problem?

Missing glad related defines using conan

First I wanted to thank you for this port. I'm getting up-to-speed with it fairly quickly and so far it's an enjoyable experience.

I just wanted to report a difficulty I had initially building the threepp library.
In src\threepp\renderers\gl\GLCapabilities.cpp, three of the defines (GL_MAX_VERTEX_UNIFORM_VECTORS, GL_MAX_VARYING_VECTORS, and GL_MAX_FRAGMENT_UNIFORM_VECTORS) were undefined when I first attempted to build.

I discovered this was related to the opengl version that glad was fetching by default. Apparently these aren't included in the opengl 3.3 compatibility extensions. I boosted the version up to opengl 4.6 compat and it resolved the issue. I'm pulling down glad via ConanCenter so it was fairly easy to change the recipe, but it definitely confused me for a short while. Thought I'd mention it in case others had trouble.

Lights seems off

E.g. pointlight gets darker as the camera gets closer and brighter the other way.

QT Creator - unresolved externals

I'm very new to threepp and vcpkg. I created the library as described and all demos are working very well. Now I wanted to create my own test application in qt creator and I'm getting the following errors. I don't understand, what I am missing...

threepp.lib(Color.obj) : error LNK2019: unresolved external symbol __std_find_trivial_1 referenced in function "char const * __cdecl __std_find_trivial<char const ,unsigned char>(char const *,char const *,unsigned char)" (??$__std_find_trivial@$$CBDE@@YAPEBDPEBD0E@Z)
threepp.lib(GLProgram.obj) : error LNK2001: unresolved external symbol __std_find_trivial_1
threepp.lib(GLUniforms.obj) : error LNK2001: unresolved external symbol __std_find_trivial_1
threepp.lib(PeripheralsEventSource.obj) : error LNK2019: unresolved external symbol __std_find_trivial_8 referenced in function "struct threepp::KeyListener * * __cdecl __std_find_trivial<struct threepp::KeyListener *,unsigned __int64>(struct threepp::KeyListener * *,struct threepp::KeyListener * *,unsigned __int64)" (??$__std_find_trivial@PEAUKeyListener@threepp@@_K@@YAPEAPEAUKeyListener@threepp@@PEAPEAU01@0_K@Z)
threepp.lib(StringUtils.obj) : error LNK2001: unresolved external symbol "unsigned int const * const std::_Large_power_data" (?_Large_power_data@std@@3QBIB)

Euler gimbal lock

Experiencing frequent gimbal locks.. Never had this issue with three.js or three.kt ..

macOS support

Do you plan to support macOS?
Right now you are targeting OpenGL 4.6 which is not supported on macOS , and the latest supported version is 4.1

Management

Make a separate dev branch from master for contributions, and pull dev to master when publishing new versions.

Failed Attempting to Build on Linux

hey folks, thanks for the great work on this project...

its prolly not a bug but i get the following error when trying to build on Ubuntu 21.10. via cmake

any thoughts?


glad/0.1.34: ERROR: Error downloading binary package: 'glad/0.1.34:7cd8e60b35bfb26d6dc0e23acc1bb0467b1b6545'
ERROR: HTTPSConnectionPool(host='center.conan.io', port=443): Max retries exceeded with url: /v1/ping (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')))

Unable to connect to conancenter=https://center.conan.io
1. Make sure the remote is reachable or,
2. Disable it by using conan remote disable,
Then try again.

i can do cpp but not so hot on conan/cmake/devops.
thanks,
sean

Loading bones using assimp

#178 added SkinnedMesh, but it has little utility without support in loaders.
I've looked briefly at the AssimpLoader, but I am at a loss on how to load skeletal information..

Help would be appriciated if animation ever should be a thing.

Summer cleanup

More intrusive changes than normal will be scheduled during the summer

  • Remove deprecated functions (#148)
  • Remove FPS from canvas (c9fd872)
  • Remove timings from canvas (#148)
  • Use Catch2 v3 (#151)
  • Allow non-owning add for Object3D (fb9d8fa)
  • Decouple GLRenderer from Canvas (#161)
  • Replacing int constants with Enums (#150) (mostly done)
  • Remove URLFetcer (#159)
  • Stack allocation of Object3D types (7ceb34f)
  • Decouple text rendering from GLRenderer (#167)

Things to look at in the future:

- [ ] Rethink physics integration
- [ ] Rethink BufferAttributes
- [ ] Less public fields
- [ ] Make it easier to add EventListeners
- [ ] Target C++20

Can you make installation procedure more clear?

I'm on OSX - this looks like a nice project!

Trying to install, I do this, all fine.

conan remote add ais https://ais.jfrog.io/artifactory/api/conan/ais-conan-local

Then on this step - I am stuck.

Then add a dependency to:
threepp/<version>@ais/stable (stable channel -> releases)
threepp/<version>@ais/testing (development builds -> master)
threepp/<version>@ais/testing-<branch> (development builds -> branches)

I am not familiar enough with conan to do this. Can you make the instructions more
clear? What command do I need to run to do this? Thanks for your help with this.

Text rendering is unstable

There is some conflict between the way gltext and threepp handles the OpenGL API, which may lead to strange behavior. Likely, threepp is missing some finalizing calls between render passes.

Drop conan

The project can be simplified a lot by dropping Conan support.

Framebuffer size and Canvas size should be different

On a Mac with Retina display the screen size is wrong and you only get an image in the bottom quater of the screen.

To fix you need to use

int width,height;
glfwGetFramebufferSize(window,&width,&height);
size_.width=width;
size_.height=height; 

In the Canvas::Impl method after window construction.

Also the resize event needs changing

  static void window_size_callback(GLFWwindow *w, int width, int height) {
      auto p = static_cast<Canvas::Impl *>(glfwGetWindowUserPointer(w));
      glfwGetFramebufferSize(w,&width,&height);
      p->size_ = {width, height};
      if (p->resizeListener) p->resizeListener.value().operator()(p->size_);
  }

It may be better to split frambuffer size and canvas size into different things as this will cause issues with some platforms. Great project BTW.

Window does not resize correctly

Ran several demos. All has the same issue.
Rendering is fine. However, when I try to resize the window, the window does not resize correctly.
The window keeps getting bigger when I drag the mouse and stop responding to the minimize, maximize and close button.
Had to press Ctrl-C at the terminal to close the window.
I'm using Ubuntu 22.04 LTS.

Assertion Failed error when minimizing application

Upon minimizing my threepp application I get an error and the program crashes with the following output:

Assertion failed: width > 0, file C:\Users\peter\Documents\vcpkg\buildtrees\threepp\src\ee0c203ca4-4c0a13da5e.clean\glte
xt.h, line 356

Process finished with exit code 3

Rendering threepp inside ImGui widget

Good day!

It's not an issue, but feature or advice request.

I use ImGui with lots of widgets and 2d plots. Now I want to have 3d visualisation, like threepp does.

I have tried to launch two ImGui windows in two different threads and different glfw and ImGui contexts, but, unfortunately, ImGui is using global variables and can have only one context inside application.

Is it possible to launch threepp with ImGui in another window?

If not. Could you, please, give me an advice on how to make threepp rendering inside ImGui widget like in this article: https://uysalaltas.github.io/2022/01/09/OpenGL_Imgui.html

Here is a gif of what it looks like:
https://uysalaltas.github.io/img/posts/OpenGL_Imgui/Scene%20Gif.gif

Kindest regards!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.