Skip to content

Instantly share code, notes, and snippets.

@zeffii
Last active August 27, 2022 18:27
Show Gist options
  • Save zeffii/0804d6fc9a48b2ed3f81da6c461020d2 to your computer and use it in GitHub Desktop.
Save zeffii/0804d6fc9a48b2ed3f81da6c461020d2 to your computer and use it in GitHub Desktop.
script for triangulated geometry
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - geometry - vertex colors</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="../files/main.css">
<style>
body {
background-color: #fff;
color: #444;
}
a {
color: #08f;
}
</style>
</head>
<body>
<div id="container"></div>
<!--<div id="info"><a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - vertex colors</div> -->
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"models": "../models/stamina.module.js"
}
}
</script>
<script type="module">
function makeid(length) {
// https://stackoverflow.com/a/1349426/1243487
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
import * as THREE from 'three';
import * as GEO from 'models';
let container, stats;
let camera, scene, renderer;
let mouseX = 0, mouseY = 0;
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
let id_storage = [];
const material = new THREE.MeshPhongMaterial( {
color: 0x66ffff,
flatShading: true,
vertexColors: false,
shininess: 0
} );
const wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, transparent: true } );
init();
add_geom_to_scene(GEO.geo);
// animate();
render();
function initiate_update_loop(time_gap){
var Interval = window.setInterval(updates, time_gap);
function updates(){
onDocumentClick(0)
}
}
initiate_update_loop(500);
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 10, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1100;
// var aspect = 1.0; // window.innerWidth / window.innerHeight;
// var d = 20;
// camera = new THREE.OrthographicCamera( - d * aspect, d * aspect, d, - d, 1, 1000 );
camera.position.set( 20, 20, 20 ); // all components equal
// camera.lookAt( 0, 0, 0 ); // or the origin
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xffffff );
const light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 0, 1 );
scene.add( light );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove );
document.addEventListener( 'click', onDocumentClick );
window.addEventListener( 'resize', onWindowResize );
}
function add_geom_to_scene(geo) {
const positions = new Float32Array(geo.obj1.verts);
const geometry1 = new THREE.BufferGeometry();
geometry1.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry1.setIndex(geo.obj1.tris);
geometry1.scale(0.5, 0.5, 0.5);
let mesh = new THREE.Mesh( geometry1, material );
id_storage.push(mesh.id);
let wireframe = new THREE.Mesh( geometry1, wireframeMaterial );
mesh.add( wireframe );
scene.add( mesh );
render();
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
}
function onDocumentClick( event) {
// function removeBysid(id) {
// scene.traverse(function(element) {
// if (element.children[0].children[0].treeNode.sid == id) {
// scene.remove(scene.getObjectById(element.id);
// // And since you know it's unique...
// return;
// }
// })
// }
console.log(id_storage);
var k = id_storage[0];
// scene.getObjectById(k).dispose(); // maybe
scene.remove(scene.getObjectById(k));
id_storage.pop();
// changing the ?num={} is what invalidates module cache. its a hack..without it
// the module is never refreshed from disk.
let resource_location = "../models/stamina.module.js?num=" + makeid(6);
import(resource_location).then(x => {
console.log('Ok');
console.log(x.geo.obj1.verts.length);
add_geom_to_scene(x.geo);
// animate();
}, err => {
console.log('Fail');
});
}
function animate() {
requestAnimationFrame( animate );
//add_geom_to_scene();
render();
}
function render() {
// camera.position.x += ( mouseX - camera.position.x ) * 0.05;
// camera.position.y += ( - mouseY - camera.position.y ) * 0.05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - geometry - vertex colors</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="../files/main.css">
<style>
body {
background-color: #fff;
color: #444;
}
a {
color: #08f;
}
</style>
</head>
<body>
<div id="container"></div>
<!--<div id="info"><a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - vertex colors</div> -->
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"models": "../models/stamina.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import * as GEO from 'models';
let container, stats;
let camera, scene, renderer;
let mouseX = 0, mouseY = 0;
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
console.log(GEO.geo.obj1);
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 10, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1100;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xffffff );
const light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 0, 1 );
scene.add( light );
const positions = new Float32Array(GEO.geo.obj1.verts);
const geometry1 = new THREE.BufferGeometry();
geometry1.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry1.setIndex(GEO.geo.obj1.tris);
geometry1.scale(20, 20, 20);
const material = new THREE.MeshPhongMaterial( {
color: 0x66ffff,
flatShading: true,
vertexColors: false,
shininess: 0
} );
const wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, transparent: true } );
let mesh = new THREE.Mesh( geometry1, material );
let wireframe = new THREE.Mesh( geometry1, wireframeMaterial );
mesh.add( wireframe );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove );
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * 0.05;
camera.position.y += ( - mouseY - camera.position.y ) * 0.05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
</body>
</html>
"""
>in verts v
>in faces s
"""
import os
import textwrap
import json
from mathutils.geometry import tessellate_polygon as tessellate
def triangles_only(verts, faces):
new_faces = []
for face in faces:
coords = [verts[idx] for idx in face]
indices = face
if len(coords) > 3:
for pol in tessellate([coords]):
new_faces.append([indices[i] for i in pol])
else:
new_faces.append(face)
verts = np.array(verts).flatten().tolist()
new_faces = np.array(new_faces).flatten().tolist()
return verts, new_faces
for vset, fset in zip(verts, faces):
_v, _f = triangles_only(vset, fset)
name = "obj1"
geom = f"""\
const geo = {{
{name}: {{
verts: {_v},
tris: {_f}
}}
}};
export {{geo}};
"""
js_name = "stamina"
top_path = r'C:\Users\zeffi\Desktop\THREEEE\models'
js_path = os.path.join(top_path, js_name + '.module.js')
with open(js_path, 'w') as f:
f.write(textwrap.dedent(geom))
import http.server
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
Handler.extensions_map={
'.manifest': 'text/cache-manifest',
'.html': 'text/html',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.svg': 'image/svg+xml',
'.css': 'text/css',
'.js': 'text/javascript',
'.module.js': 'module',
'': 'application/octet-stream'
}
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment