HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>ShapeDiver Viewer v2</title>
<!-- ShapeDiver Viewer -->
<script defer src="https://viewer.shapediver.com/v2/staging/sdv.concat.min.js"></script>
<link rel='stylesheet' type='text/css' href="https://viewer.shapediver.com/v2/2.22/sdv.css">
<!-- ShapeDiver Viewer Controls and Export Modal Dialog Dependencies -->
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.1.5/css/uikit.min.css" integrity="sha256-sO/kKFCHPL4rhYHDyHC2dwGlaIBttifOfQ0ZaGLAheo=" crossorigin="anonymous" />
<!-- UIkit JS -->
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.1.5/js/uikit.min.js" integrity="sha256-jN++RwBoYassp9qTuZDfQuptszFdL1Pm4dKZWS5KjjY=" crossorigin="anonymous"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.1.5/js/uikit-icons.min.js" integrity="sha256-6pktS+jePPdXx9oCn8r4hS5jR1eq0Ry7vbifYtG0LDU=" crossorigin="anonymous"></script>
</head>
<body>
<!-- Images for starting external drag events -->
<div style="width: 100%; height: 50px; position: absolute; float: right;">
<img id="drawer_new" draggable="false", src="https://dummyimage.com/200x50/000/fff/&text=Drawer" style="width:25%; height:100%" title="Logo" alt="Logo"/>
<img id="shelf_new" draggable="false", src="https://dummyimage.com/200x50/000/fff/&text=Shelf" style="width:25%; height:100%" title="Logo" alt="Logo"/>
<img id="clothes_rail_new" draggable="false", src="https://dummyimage.com/200x50/000/fff/&text=Rail" style="width:25%; height:100%" title="Logo" alt="Logo"/>
</div>
<!-- ShapeDiver Viewer Main Container -->
<div id='sdv-container' style='top: 50px' class='shapediver-container-flex shapediver-container-fullsize'
sdv-fullscreen="true">
<!-- ShapeDiver Viewer Settings Controls Container -->
<div id='sdv-container-settings' class='shapediver-settings-flex' style='display: none;'></div>
<!-- ShapeDiver Viewer Viewport Container -->
<div class='shapediver-viewport-flex'>
<div id='sdv-container-viewport' class='shapediver-container-fullsize' style='opacity: 0;'
logginglevel=0 messagelogginglevel=2>
</div>
<!-- The loading icon will be created here -->
</div>
<!-- ShapeDiver Viewer Parameter Controls Container -->
<div id='sdv-container-controls' class='shapediver-controls-flex' style='display: none;'></div>
</div>
<script src="init.js" defer></script>
</body>
</html>
const INTERACTION_GROUP_ELEMENTS = 'elements';
const INTERACTION_GROUP_ELEMENTS_NEW = 'elements_new';
const INTERACTION_GROUP_PROXIES = 'proxies';
const PROXY_ASSET_ID_POSTFIX = '_proxy';
class ProductLogic {
constructor(api) {
// keep a reference to the viewer API
this.api = api;
// defines the assets of the default scene
this.ASSET_DEFINITIONS = {
cabinet: {
content: [
{
href:
"https://shapediverexternalgeometry.s3.amazonaws.com/wardrobe/220_8150_cabinet_987mm_484mm.glb",
format: "glb"
},
//{
// format: "material",
// data: {
// version: '2.0',
// color: 'red'
// }
//}
],
defaultPosition: new THREE.Matrix4()
},
drawer: {
content: [
{
href:
"https://shapediverexternalgeometry.s3.amazonaws.com/wardrobe/220_287_Drawer_987mm.glb",
format: "glb"
}
],
defaultPosition: [
(new THREE.Matrix4()).makeTranslation(16, 20, 100),
(new THREE.Matrix4()).makeTranslation(16, 20, 270)
],
interactionGroup: INTERACTION_GROUP_ELEMENTS
},
clothes_rail: {
content: [
{
href:
"https://shapediverexternalgeometry.s3.amazonaws.com/wardrobe/231_231_clothes_rail_987mm.glb",
format: "glb"
}
],
defaultPosition: (new THREE.Matrix4()).makeTranslation(16, 285, 1900),
interactionGroup: INTERACTION_GROUP_ELEMENTS
},
shelf: {
content: [
{
href:
"https://shapediverexternalgeometry.s3.amazonaws.com/wardrobe/231_261_shelf_987mm.glb",
format: "glb"
}
],
defaultPosition: [
(new THREE.Matrix4()).makeTranslation(16, 20, 800),
(new THREE.Matrix4()).makeTranslation(16, 20, 460)
],
interactionGroup: INTERACTION_GROUP_ELEMENTS
}
};
// defines which proxies to show depending on type of asset being dragged
this.PROXY_SLOTS = {
drawer: {
basePosition: (new THREE.Matrix4()).makeTranslation(16, 20, 100),
height: 170,
count: 12
},
clothes_rail: {
basePosition: (new THREE.Matrix4()).makeTranslation(16, 285, 100),
height: 50,
count: 41
},
shelf: {
basePosition: (new THREE.Matrix4()).makeTranslation(16, 20, 100),
height: 40,
count: 51
}
};
// material to use for proxies
this.PROXY_MATERIAL_CONTENT_ITEM = {
format: 'material',
data: {
version: '2.0',
color: 'rgb(180,180,180)',
transparency: 0.5
}
};
// last saved state of assets
this.wardrobeAssets = null;
// proxy assets currently part of the scene
this.proxyAssets = null;
// item data for the currently hovered item (if any)
this.hoveredItemData = null;
// #SS-2092
this.wasUp = false;
this.resetUp = () => { this.wasUp = false; };
document.addEventListener('mouseup', () => { this.wasUp = true; });
}
/**
* Get default asset by name from internal database
*/
getDefaultAssetByName(name) {
let asset = { id: name, version: "default", content: [] };
let namedAsset = this.ASSET_DEFINITIONS[name];
if (namedAsset) {
asset.content = JSON.parse(JSON.stringify(namedAsset.content));
if (namedAsset.defaultPosition) {
asset.content.forEach(
item => (item.transformations = Array.isArray(namedAsset.defaultPosition) ? namedAsset.defaultPosition : [namedAsset.defaultPosition])
);
}
if (namedAsset.interactionGroup) {
asset.interactionGroup = namedAsset.interactionGroup;
asset.dragPlaneNormal = [0,1,0];
asset.interactionMode = 2; // we want interaction tp happen at the level of transformations
}
}
return asset;
}
/**
* Default assets to initialize the wardrobe with
*/
getDefaultAssets() {
let assets = [];
for (let name in this.ASSET_DEFINITIONS) {
let asset = this.ASSET_DEFINITIONS[name];
if (asset.defaultPosition) {
assets.push(this.getDefaultAssetByName(name));
}
}
return assets;
}
/**
* Get new asset for dragging from "outside" the viewer
*/
getNewAssetForDraggingByName(name) {
let asset = { id: name + '_new', version: 'default', content: [] };
let namedAsset = this.ASSET_DEFINITIONS[name];
if (namedAsset) {
asset.content = JSON.parse(JSON.stringify(namedAsset.content));
if (namedAsset.defaultPosition) {
asset.content.forEach(
item => {delete item.transformations;}
);
}
asset.interactionGroup = INTERACTION_GROUP_ELEMENTS_NEW;
asset.dragPlaneNormal = [0,1,0];
asset.interactionMode = 2; // we want interaction to happen at the level of transformations
}
return asset;
}
/**
* Default light scene
*/
getDefaultLightScene() {
return {
"id": "scene_1",
"lights": {
"ambient0": {
"id": "ambient0",
"type": "ambient",
"properties": {
"color": "white",
"intensity": 0.5
}
},
"directional0": {
"id": "directional0",
"type": "directional",
"properties": {
"color": "rgb(255, 252, 249)",
"intensity": 0.5,
"castShadow": true,
"direction": {
"x": 0.5774,
"y": -0.5774,
"z": 0.5774
}
}
},
"directional1": {
"id": "directional1",
"type": "directional",
"properties": {
"color": "rgb(255, 251, 231)",
"intensity": 0.5,
"castShadow": true,
"direction": {
"x": -0.25,
"y": -1,
"z": 0.6
}
}
},
"SPOT": {
"id": "SPOT",
"type": "spot",
"properties": {
"color": "rgb(255, 242, 184)",
"intensity": 0.4,
"distance": 0,
"angle": 0.34,
"penumbra": 0.49,
"decay": 0.19,
"position": {
"x": 855.1426952119964,
"y": -1688.8295554696597,
"z": -148.4294032070402
},
"target": {
"x": 741.3149983403828,
"y": 737.2080705888891,
"z": 2389.0669602811713
}
}
}
}
};
}
/**
* Default viewer settings
*/
getDefaultSettings() {
return {
scene: {
render: {
//clearColor: '#FF0000'
},
camera: {
defaults: {
perspective: {
position: {x: -1e4, y: -3e4, z: 7e3},
target: {x: 0, y: 0, z: 0}
}
},
zoomExtentsFactor: 1.25
}
}
};
}
/**
* Default interaction groups for wardrobe elements and proxies
*/
getDefaultInteractionGroups() {
return [
{
id: INTERACTION_GROUP_ELEMENTS,
hoverable: true,
hoverEffect: {
active: {
name: 'colorHighlight',
options: {
color: 'rgb(255, 179, 31)'
}
}
},
draggable: true
},
{
id: INTERACTION_GROUP_ELEMENTS_NEW,
draggable: true
},
{
id: INTERACTION_GROUP_PROXIES,
hoverable: true,
hoverEffect: {
active: {
name: 'colorHighlight',
options: {
color: 'rgb(0, 165, 255)'
}
}
},
}
];
}
/**
* Get proxy geometry for the given dragged item
*
* This contains some dumb placeholder logic, not taking care of
* the current configuration.
*/
getProxyGeometryAssetsForItem(itemData) {
let itemId = itemData.id;
if (itemId.endsWith('_new')) {
itemId = itemId.substring(0, itemId.length - 4);
}
// compose an array of transformations to place proxy geometry
let proxyData = this.PROXY_SLOTS[itemId];
let position = proxyData.basePosition.clone();
let translation = (new THREE.Matrix4()).makeTranslation(0, 0, proxyData.height);
let transformations = [];
for ( let i=0; i<proxyData.count; i++) {
transformations.push( position );
position = position.clone().multiply(translation);
}
// use the original geometry of the dragged item for proxy geometry
let asset = this.getDefaultAssetByName(itemId);
asset.id = asset.id + PROXY_ASSET_ID_POSTFIX;
asset.content.forEach(
item => (item.transformations = transformations)
);
return [asset];
}
/**
* Add proxy geometry for the given dragged item to the scene
*/
async addProxyGeometryForItem(itemData) {
if (!this.proxyAssets) {
this.proxyAssets = this.getProxyGeometryAssetsForItem(itemData);
this.proxyAssets.forEach(
item => {
item.interactionGroup = INTERACTION_GROUP_PROXIES;
item.content.push( this.PROXY_MATERIAL_CONTENT_ITEM );
}
);
console.time('api.scene.updateAsync');
const result = await this.api.scene.updateAsync(this.proxyAssets);
console.timeEnd('api.scene.updateAsync');
return result;
}
}
/**
* Remove all proxy geometry from the scene
*/
removeProxyGeometry() {
this.proxyAssets = null;
return this.api.scene.removeAsync({interactionGroup: INTERACTION_GROUP_PROXIES});
}
/**
* Remove external drag geometry
*/
removeExternalDragGeometry(itemData) {
if (itemData.id.endsWith('_new')) {
return this.api.scene.removeAsync({id: itemData.id});
}
}
/**
* Get transformation of a proxy asset content item
*/
getProxyTransformation(itemData) {
if (!this.proxyAssets) return;
let asset = this.proxyAssets.find((asset) => asset.id === itemData.id);
if (!asset) return;
return asset.content[itemData.content].transformations[itemData.transformation];
}
/**
* Parse a scene path, return an object containing the:
* - id: asset item id
* - content: index into the content array of the asset
* - transformation: index into the transformation array of the content item
*/
getItemDataFromScenePath(scenePath) {
let parts = scenePath.split('.');
return {
id: parts[1],
content: parts.length > 2 ? parseInt(parts[2].split('_')[1]) : null,
transformation: parts.length > 3 ? parseInt(parts[3].split('_')[1]) : null
}
}
/**
* Compute the squared euclidean length of a vector
*/
vectorLengthSquared(v) {
return v.x*v.x + v.y*v.y + v.z*v.z;
}
handleDragStart(event) {
let itemData = this.getItemDataFromScenePath(event.scenePath);
console.log(event.type, itemData, event);
}
handleDragMove(event) {
let itemData = this.getItemDataFromScenePath(event.scenePath);
//console.log(event.type, itemData, event);
// add hoverable proxy geometry (if none)
this.addProxyGeometryForItem(itemData);
}
handleDragEnd(event) {
let itemData = this.getItemDataFromScenePath(event.scenePath);
console.log(event.type, itemData, event);
// if dragging was just a click, zoom to the scenePath
if ( this.vectorLengthSquared(event.dragPosRel) < 1e-6 ) {
this.api.scene.camera.zoomAsync([event.scenePath]);
return;
}
// check if a proxy geometry was hovered, update or reset position of dragged object accordingly
if (this.hoveredItemData && this.hoveredItemData.id.endsWith(PROXY_ASSET_ID_POSTFIX)) {
let transformation = this.getProxyTransformation(this.hoveredItemData);
this.setWardrobeItemTransformation(itemData, transformation);
}
// remove hoverable proxy geometry (if any)
this.removeProxyGeometry();
// remove external drag geometry (if any)
this.removeExternalDragGeometry(itemData);
// update assets
this.resetWardrobeAssets(itemData);
}
handleHoverOn(event) {
let itemData = this.getItemDataFromScenePath(event.scenePath);
//console.log(event.type, itemData, event);
// remember currently hovered asset
this.hoveredItemData = itemData;
}
handleHoverOff(event) {
//let itemData = this.getItemDataFromScenePath(event.scenePath);
//console.log(event.type, itemData, event);
// reset currently hovered asset
this.hoveredItemData = null;
}
/**
* Set transformations for the given item
*/
setWardrobeItemTransformation(itemData, transformation) {
let itemId = itemData.id;
let newItem = false;
if (itemId.endsWith('_new')) {
itemId = itemId.substring(0, itemId.length - 4);
newItem = true;
}
let asset = this.wardrobeAssets.find((asset) => asset.id === itemId);
console.log(itemId, asset);
if (!asset) return;
if (newItem) {
asset.content[itemData.content].transformations.push(transformation);
}
else {
asset.content[itemData.content].transformations[itemData.transformation] = transformation;
}
}
/**
* Replace the current state of the wardrobe assets,
* and update the scene.
*/
setWardrobeAssets(assets) {
this.wardrobeAssets = assets;
//console.log('wardrobe assets', assets);
return this.api.scene.updateAsync(assets);
}
/**
* Reset the wardrobe assets to their last known state,
* typically the state before a dragging operation.
* Optionally reset a selected asset only.
*/
resetWardrobeAssets(itemData) {
this.wardrobeAssets.forEach((asset) => {
if ( !itemData || itemData.id.startsWith(asset.id) ) {
asset.version = this.api.utils.createRandomId();
}
});
return this.api.scene.updateAsync(this.wardrobeAssets);
}
/**
* Update interaction group for wardrobe assets which already have an interaction group
*/
setWardrobeInteractionGroup(group) {
this.wardrobeAssets.forEach((asset) => {
if (asset.interactionGroup) {
asset.interactionGroup = group;
}
});
return this.resetWardrobeAssets();
}
/**
* Handler for starting external drag event
* - adds asset for dragging to scene, hides it immediately
* - tells the viewer that external dragging started
*/
async handleExternalDragStart(eventType, name) {
// #SS-2092
this.resetUp();
console.log('external drag start', name);
let asset = this.getNewAssetForDraggingByName(name);
let res = await api.scene.updateAsync(asset);
this.api.scene.toggleGeometry([], res.data[0].scenePath);
// #SS-2092
if(this.wasUp === false) {
this.api.scene.startExternalDragEvent(res.data[0].scenePath, eventType);
} else {
await api.scene.removeAsync({id: asset.id});
}
};
};
/**
* ShapeDiver viewer initialisation
*/
async function initSdvApp () {
// Constructor settings can be defined here, or as attributes of the viewport container.
// Settings defined here take precedence.
let settings = {
showControlsButton: false,
showControlsInitial: false,
showSettingsInitial: false,
showBusySpinner: false,
loggingLevel: -1,
messageLoggingLevel: 3
};
// See https://viewer.shapediver.com/v2/2.14.0/doc/SDVApp.ParametricViewer.html
// for all settings available via the constructor.
let api = new SDVApp.ParametricViewer(settings);
window.api = api;
// create product logic
let logic = new ProductLogic(api);
window.logic = logic;
window.api.scene.addEventListener(window.api.scene.EVENTTYPE.VISIBILITY_ON, () => {
setTimeout(() => {api.scene.camera.zoomAsync();})
});
// default settings
await api.updateSettingsAsync(logic.getDefaultSettings());
await api.updateSettingAsync('scene.camera.defaults.perspective', logic.getDefaultSettings().scene.camera.defaults.perspective);
// restore light scene
await api.scene.lights.setLightSceneFromDefinition(logic.getDefaultLightScene());
// create interaction groups
await api.scene.updateInteractionGroups(logic.getDefaultInteractionGroups());
// set up event handlers
api.scene.addEventListener(api.scene.EVENTTYPE.HOVER_ON, (e) => logic.handleHoverOn(e));
api.scene.addEventListener(api.scene.EVENTTYPE.HOVER_OFF, (e) => logic.handleHoverOff(e));
api.scene.addEventListener(api.scene.EVENTTYPE.DRAG_START, (e) => logic.handleDragStart(e));
api.scene.addEventListener(api.scene.EVENTTYPE.DRAG_MOVE, (e) => logic.handleDragMove(e));
api.scene.addEventListener(api.scene.EVENTTYPE.DRAG_END, (e) => logic.handleDragEnd(e));
// event handlers for externally triggered dragging (adding of new elements)
['drawer','shelf','clothes_rail'].forEach(name => {
let elem = document.getElementById(name + '_new');
elem.addEventListener('mousedown', () => logic.handleExternalDragStart('mouse', name));
elem.addEventListener('touchstart', () => logic.handleExternalDragStart('touch', name));
});
// setup default scene
await logic.setWardrobeAssets(logic.getDefaultAssets());
};
// there is a slight chance that loading has been completed already
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initSdvApp, false);
} else {
initSdvApp();
}
Also see: Tab Triggers