Is it possible to know programmatically the position of texture in ruby? - ruby

I written some plugins for sketch-up. I want to know that is it possible to know the texture position that is vertical or horizontal programmatically in ruby ?
Ex: I'm using Sketch-up for wood working and whenever I apply material to the model I should take care of grains. So that I want to know that the wood grains are in horizontal or vertical. Selecting face then clicking Texture->position we can make horizontal grains to vertical and vice-verse. After applying materials programmatically how should I know the grains are horizontal or vertical.
Is there any solution?

When you say horizontal and vertical that implies from general direction - do you have that via Ruby code some how? Do you determine via the bounds of the group/component?
You can use face.getUVHelper to extract the position of the texture on the face. (You can also do so via PolygonMesh - but that's only really useful if you are interested in all the other data you get from that.)
Once you have the UV position you can use that to compare against your desired direction. (This would also assume that all your textures have the grain in the same direction.) Based on that you can then reposition the texture using face.position_texture.
Edit: a very native version can be seen in my UV Toolkit plugin. It's a very old plugin and not the greatest example - it enforces restrictions that the face must be a quad and only rotates in 90 degrees. But it shows how to get UV data and change the orientation of the texture.
A better generic version would be to get four points of the plane of the face (not colinear) and get the UV data for each point. Then transform the UV data by the rotation needed to get the direction you want and set the new UV data.

Disclaimer
I am horrible with 3-Dimensions (so please don't ask for help with the appropriate vectors) and I have never used sketchup ever. Not even once until right now but...
Information
You must select the Face object.
model = Sketchup.active_model
entities = model.active_entities
face_entities = entities.find_all{|e| e.class == Sketchup::Face}
#=>[#<Sketchup::Face:0xea645d8>]
face_entities.each{|e| puts e.get_texture_projection(false)}
#=> output of each texture projection for the back side
#nil means that the projection is unchanged from it's initial position
So here is what you can do
#true returns front, false returns the back texture as a Vector object
get_texture_projection(true || false)
#submit a vector [0,1,0] || nil , true sets front || false sets the back
#nil will reset the projection back to it's initial position
set_texture_projection([0,1,0],true || false)
#texture is now rotated 90 degrees on the Y axis
set_texture_projection([1,0,0],true || false)
#texture is now rotated 90 degrees on the X axis
you can also access the material through material and back_material
face.material.name
#=> [Wood_ Floor]
face.material.texture.filename
#=>Wood_Floor.jpg
Hope this helps you out it took a bit of digging but based on using the built in console in Sketchup it works.
P.S. I love that this program has a built in Ruby API that's is awesome.

Related

ThreeJS flip reversed X axis (left handed coordinate system)

I'm trying to create this 3D tile system world merged from smaller 3D objects - in order create these we use another application made in Unity which loads all small 3D assets separate and may be used to create your new model. Upon saving these model files there will be a JSON file created which contains all scales, positions, rotation etc. of all used 3D models.
We have decided to use this system of 'North, East, South, West' to make sure everything will look good in production. However now when we're trying to render these same JSON files in ThreeJS we have noticed the X axis is reversed compared to the Unity application that we're using .
What we want is this:
North is increasing Z value (north and south are fine)
East is increasing X value
West is decreasing X value
At the moment this is what's going wrong in ThreeJS:
East is decreasing X value
West is increasing X value
What we already have tried is this:
mirror / flip the camera view
when a coordinate drops below 0 we make it absolute (-10 will be 10)
when a coordinate is above 0 we make it negative (10 will be -10)
But nothing of the above had the desired effect. Reversing the coordinates with code brings other problems when it comes to scaled, rotated objects that are smaller or larger than 1x1x1 size. Ideally would be that we don't have to change our coordinates and that still can be used as a solid reference by changing the direction of the X axis from the left side to the right side of 0,0,0
Currently ThreeJS uses the 'right handed coordinate system' and what we desire is a left handed coordinate system. Is this something that is possible to configure within ThreeJS?
Anyone an idea what i can try except flipping all X coordinates?
It's not something you can configure in three.js or Unity. Different file formats typically have a notional coordinate system built into them. GLTF, for example, is represented in a right-handed coordinate system. It's the responsibility of the format importers and exporters to handle the conversion -- this is what the builtin three.js importers do.
I would suggest using an existing format such as GLTF to represent your scene (there is an existing Unity exporter available and an importer available for three.js).
Or if you'd like to retain control over your own file format you can do the left to right handed coordinate system conversion yourself either at export from Unity or import to three.js. Looking at your image it looks like you'll want to multiple all of the X values by -1.0 to get them to look the same. You'll want to save your rotations as quaternions, as well, to avoid rotation order differences.
Of course you could always just scale the whole scene by -1.0 on X but that may make it difficult to work with other parts of three.js.
I would consider to apply a (-1, 1, 1) scale to the root of your "Unity exported scene", this way you can still keep the other part of your scene unchanged.
obj3d.scale.set(-1, 1, 1);

Possibly to prioritise drawing of objects in Threejs?

I am working on a CAD type system using threejs. I have thin objects next to other objects (think thin 2mm metal sheeting fixed to posts on a building measured in metres). When I am zoomed in it all looks fine. The objects do not intersect at all. As I zoom out the objects get smaller and I end up with cases where the post object 'glimmers' (sort of shows through) the metal sheet object as I rotate it around.
I understand it's the small numbers I am working with that is causing this effect. However, is there a way to set a priority such that one object (the metal sheeting) is more important than another object (post) so it doesn't get that sort of effect?
To answer the question from the title, it is possible to prioritize drawing orders with.
myMesh.renderOrder = 5
myOtherMesh.renderOrder = 7
It is then possible to apply different depth effects, turn off the test etc.
Another way is to group objects with, layers. Set the appropriate layer mask on the camera and then render (multiple times).
myMesh.layers.set(5)
camera.layers.set(1)
renderer.render(scene,camera)
camera.layers.set(5)
renderer.render(scene,camera)
This is called z-fighting, where two fragments are so close in the given depth space that their z-values are within the margin of error that their true depths might get inverted.
The easiest way to resolve this is to reduce the scale of your depth buffer. This is controlled by the near and far properties on your camera. You'll need to play with the values to determine what works best for your senario. If you can minimize the distance between the planes, you'll have better luck avoiding z-fighting.
For example, if (as a loose estimate) the bounding sphere of your entire model has a diameter of 100, then the distance between near and far need only be 100. However, their values are set as the distance into camera space. So as you zoom out, and your camera moves further away, you should adjust the values to maintain the minimum distance between them. If your camera is at z = 100, then set near = 50 and far = 150. When you pull your camera back to z = 250, then update near = 200 and far = 300.
Another option is to use the WebGLRenderer.logarithmicDepthBuffer option. (example)
Edit: There is one other cause: the faces of the shapes are actually co-planar. If two triangles are occupying the same space, then you're all but guaranteeing z-fighting.
The simple solution is to move one of the components such that the faces are no longer co-planar. You could also potentially apply a polygonOffset to the sheet metal material, but your use-case doesn't sound like that is appropriate.

Find which object3D's the camera can see in Three.js - Raycast from each camera to object

I have a grid of points (object3D's using THREE.Points) in my Three.js scene, with a model sat on top of the grid, as seen below. In code the model is called default mesh and uses a merged geometry for performance reasons:
I'm trying to work out which of the points in the grid my perspective camera can see at any given point i.e. every time the camera position is update using my orbital controls.
My first idea was to use raycasting to create a ray between the camera and each point in the grid. Then I can find which rays are being intersected with the model and remove the points corresponding to those rays from a list of all the points, thus leaving me with a list of points the camera can see.
So far so good, the ray creation and intersection code is placed in the render loop (as it has to be updated whenever the camera is moved), and therefore it's horrendously slow (obviously).
gridPointsVisible = gridPoints.geometry.vertices.slice(0);
startPoint = camera.position.clone();
//create the rays from each point in the grid to the camera position
for ( var point in gridPoints.geometry.vertices) {
direction = gridPoints.geometry.vertices[point].clone();
vector.subVectors(direction, startPoint);
ray = new THREE.Raycaster(startPoint, vector.clone().normalize());
if(ray.intersectObject( defaultMesh ).length > 0){
gridPointsVisible.pop(gridPoints.geometry.vertices[point]);
}
}
In the example model shown there are around 2300 rays being created, and the mesh has 1500 faces, so the rendering takes forever.
So I 2 questions:
Is there a better of way of finding which objects the camera can see?
If not, can I speed up my raycasting/intersection checks?
Thanks in advance!
Take a look at this example of GPU picking.
You can do something similar, especially easy since you have a finite and ordered set of spheres. The idea is that you'd use a shader to calculate (probably based on position) a flat color for each sphere, and render to an off-screen render target. You'd then parse the render target data for colors, and be able to map back to your spheres. Any colors that are visible are also visible spheres. Any leftover spheres are hidden. This method should produce results faster than raycasting.
WebGLRenderTarget lets you draw to a buffer without drawing to the canvas. You can then access the render target's image buffer pixel-by-pixel (really color-by-color in RGBA).
For the mapping, you'll parse that buffer and create a list of all the unique colors you see (all non-sphere objects should be some other flat color). Then you can loop through your points--and you should know what color each sphere should be by the same color calculation as the shader used. If a point's color is in your list of found colors, then that point is visible.
To optimize this idea, you can reduce the resolution of your render target. You may lose points only visible by slivers, but you can tweak your resolution to fit your needs. Also, if you have fewer than 256 points, you can use only red values, which reduces the number of checked values to 1 in every 4 (only check R of the RGBA pixel). If you go beyond 256, include checking green values, and so on.

How to change the rotation order in cocos3d

I'm a fresh in cocos3d, now I have a problem.
In cocos3d, I want to rotate a node. I got the angles in x axis, y axis, z axis, then I used the property:rotation to rotate, like this:
theNodeToBeRotated.rotation = cc3v(x,y,z);
But I found out it didn't rotate as I expected, because the document said the rotate order is y-x-z.
I want to change the order to x-y-z. Can anyone let me know how?
You might need to clarify further regarding the following: "it didn't rotate as I expected"
OpenGL ES (and ergo, cocos3D) uses the y-axis as up so the rotation order is still x-y-z. If you are importing a model, you then need to take into account the 3D editor's co-ordinate system and adapt accordingly.
If you are not used to working with three-dimensional representations, the leap from 2D to 3D can be a significant hurdle. Within Cocos3D:
the x-axis is positive on the right and negative on the left
the y-axis is positive upwards and negative downwards
the z-axis is positive moving towards you and negative moving away from you
Envisage those three lines of axis, or even better, a piece of string.
If you are rotating around the x-axis, hold the string horizontally from left to right: the object would rotating towards you or away from you.
If you are rotating around the y-axis, hold the string vertically from feet to head: the object would rotate as if like a revolving door.
If you are rotating around the z-axis, hold one end close to your chest and the other end as far away as possible: the object would rotate similar to a clock face.
-- Update
I heavily wouldn't recommend changing the rotation order as it is the OpenGL standard to use Y-X-Z. If you wish to modify it, take a look at CC3GLMatrixMath and look for kmMat4RotationYXZ - there is also kmMat4RotationZYX. If you want to have X-Y-Z, you would need to construct your own rotation matrix and update accordingly in CC3GLMatrix and CC3GLMatrixMath.
As a reference, you also have the OpenGL Red book - it should have some suggestions for you.

Drawing 3D in front/behind sprites in XNA/WP7?

This is kind of frustrating me as I've been grizzling over it for a couple of hours now.
Basically I'm drawing 2D sprites through spritebatch and 3D orthographically projected geometry using the BasicEffect class.
My problem is controlling what gets rendered on top of what. At first I thought it would be simply controlling the render order, i.e. if I do:
Draw3DStuff()
SpriteBatch.Begin(...)
Draw2DStuff();
SpriteBatch.End();
It would mean the 2D stuff would render over the 3D stuff, however since I don't control when the device begins/ends renders this isn't the result. The 3D always renders on top of the 2D elements, no matter the projection settings,world translation, the z components of the 3D geometries vertex definitions and the layer depth of the 2D elements.
Is there something I'm not looking into here?
What's the correct way to handle the depth here?
OK I figured it out 2 seconds after posting this question. I don't know if it was coincidence or if StackOverflow has a new feature granting the ability to see future answers.
The Z position of spritebatch elements are between 0 and 1 so they're not directly comparable to the z positions of orthographic geometry being rendered.
When you create an orthographic matrix however you define a near and far clip plane. The Z pos you set should be within this clip plane. I had a hunch that the spritebatch class is effectively drawing quads orthographically so by extension that 0 to 1 would mean 0 was representing a near clip and 1 a far clip, and the depth was probably being rendered into the same place the 3D geometry depth is being rendered to.
Soooo, to make it work I just figured that the near/far clips I was defining for the orthographic render will be measured against the near/far clips of the sprites being rendered, so it was simply a matter of setting the right z value, so for example:
If I have a near clip of 0 and a far clip of 10000 and I wanted to draw it so that it would correspond to 0.5f layer depth and render in front of sprites being drawn at 0.6 and behind sprites being drawn at 0.4 I do:
float zpos = 0.5f;
float orthoGraphicZPos = LinearInterpolate(0, 10000, zpos);
Or just zpos * 10000 :D
I guess it would make more sense to have your orthographic renderers near/far clip to be 0 and 1 to directly compare with the sprites layer depths.
Hopefully my reasoning for this solution was correct (more or less).
As an aside, since you mentioned you had a hunch on how the sprite batch was drawing quads. You can see the source code for all the default/included shaders and the spritebatch class if you are curious, or need help solving a problem like this:
http://create.msdn.com/en-US/education/catalog/sample/stock_effects
The problem is that the spritebatch messes with some of the renderstates that are used when you draw your 3d objects. To fix this you just have to reset them before rendering your 3d objects like so.
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
Draw3DStuff()
SpriteBatch.Begin(...)
Draw2DStuff();
SpriteBatch.End();
Note that this is for xna 4.0 which I am pretty sure your using anyway. More info can be found on shawn hargreaves blog here. This will draw the reset the render states, draw the 3d objects, then the 2d objects over them. Without resetting the render states you get weird effects like your seeing.

Resources