public override bool TryFrom(PrimitiveList pl, Type targetType, out object result) { var elementType = Utils.GetPrimitiveElementType(targetType); var primitives = pl.Entries; return(EntriesToCollection(targetType, elementType, pl.Entries.Cast <DynamoDBEntry>(), out result)); }
public object FromEntry(DynamoDBEntry entry) { PrimitiveList pList = entry as PrimitiveList; if (pList != null) { double lat = 0, lon = 0, accuracy = 0; for (int i = 0; i < pList.Entries.Count; i++) { switch (i) { case 0: lat = pList [i].AsDouble(); break; case 1: lon = pList [i].AsDouble(); break; case 2: accuracy = pList [i].AsDouble(); break; default: break; } } return(new Coordinate(lat, lon, accuracy)); } else { return(null); } }
public void Compile() { if (root.PrimitiveCount == 0) // nothing to compile return; // calc bounding box root.boundingBox = surroundingBox(root.primitives); bigObjects = new PrimitiveList(); for (int i = 0; i < root.primitives.Count; i++) { if (isBigBoundingBox(root.primitives[i].BoundingBox, root.boundingBox)) { Primitive bigObject = root.primitives[i]; bigObjects.Add(bigObject); root.primitives.Remove(bigObject); i--; } } // recalc bounding box root.boundingBox = surroundingBox(root.primitives); // split root root.SplitRecursively(MaxObjectsInNode, 0, MaxTreeDepth); compiled = true; }
private void tesselate() { lock (lockObj) { // double check flag if (builtTess != 0) { return; } if (tesselatable != null && primitives == null) { UI.printInfo(UI.Module.GEOM, "Tesselating geometry ..."); primitives = tesselatable.Tesselate(); if (primitives == null) { UI.printError(UI.Module.GEOM, "Tesselation failed - geometry will be discarded"); } else { UI.printDetailed(UI.Module.GEOM, "Tesselation produced {0} primitives", primitives.getNumPrimitives()); } } builtTess = 1; } }
public void build(PrimitiveList primitives) { this.primitives = primitives; int n = primitives.getNumPrimitives(); UI.printDetailed(UI.Module.ACCEL, "Getting bounding box ..."); bounds = primitives.getWorldBounds(null); objects = new int[n]; for (int i = 0; i < n; i++) { objects[i] = i; } UI.printDetailed(UI.Module.ACCEL, "Creating tree ..."); int initialSize = 3 * (2 * 6 * n + 1); List <int> tempTree = new List <int>((initialSize + 3) / 4); BuildStats stats = new BuildStats(); Timer t = new Timer(); t.start(); buildHierarchy(tempTree, objects, stats); t.end(); UI.printDetailed(UI.Module.ACCEL, "Trimming tree ..."); tree = tempTree.ToArray(); // display stats stats.printStats(); UI.printDetailed(UI.Module.ACCEL, " * Creation time: {0}", t); UI.printDetailed(UI.Module.ACCEL, " * Usage of init: {0,9:0.00}%", (double)(100 * tree.Length) / initialSize); UI.printDetailed(UI.Module.ACCEL, " * Tree memory: {0}", Memory.SizeOf(tree)); UI.printDetailed(UI.Module.ACCEL, " * Indices memory: {0}", Memory.SizeOf(objects)); }
public object FromEntry(DynamoDBEntry entry) { PrimitiveList primList = entry as PrimitiveList; if (primList == null) { throw new ArgumentOutOfRangeException(); } List <Comment> comments = new List <Comment>(); foreach (string s in primList.AsListOfString()) { string[] data = s.Split(new string[] { "$~$" }, StringSplitOptions.None); if (data.Length != 4) { throw new ArgumentOutOfRangeException(); } Comment record = new Comment { CommentId = Convert.ToString(data[0]), Rating = Convert.ToDecimal(data[1]), UserId = Convert.ToString(data[2]), CommentContent = Convert.ToString(data[3]) }; comments.Add(record); } return(comments); }
// DynamoDBEntry <--> Object private static object FromDynamoDBEntry(PropertyStorage propertyStorage, DynamoDBEntry value) { var converter = propertyStorage.Converter; if (converter != null) { return(converter.FromEntry(value)); } object output; var targetType = propertyStorage.MemberType; Primitive primitive = value as Primitive; if (primitive != null && TryFromPrimitive(targetType, primitive, out output)) { return(output); } PrimitiveList primitiveList = value as PrimitiveList; if (primitiveList != null && TryFromPrimitiveList(targetType, primitiveList, out output)) { return(output); } throw new InvalidOperationException( string.Format("Unable to convert attribute \"{0}\" to property \"{1}\" of type \"{2}\"", propertyStorage.AttributeName, propertyStorage.PropertyName, propertyStorage.MemberType.FullName)); }
// DynamoDBEntry <--> Object private static object FromDynamoDBEntry(Type targetType, DynamoDBEntry value, IPropertyConverter converter) { if (converter != null) { return(converter.FromEntry(value)); } object output; Primitive primitive = value as Primitive; if (primitive != null && TryFromPrimitive(targetType, primitive, out output)) { return(output); } PrimitiveList primitiveList = value as PrimitiveList; if (primitiveList != null && TryFromPrimitiveList(targetType, primitiveList, out output)) { return(output); } throw new InvalidOperationException("Unable to convert to type " + targetType.FullName); }
public void build(PrimitiveList primitives) { this.primitives = primitives; int n = primitives.getNumPrimitives(); UI.printDetailed(UI.Module.ACCEL, "Getting bounding box ..."); bounds = primitives.getWorldBounds(null); objects = new int[n]; for (int i = 0; i < n; i++) objects[i] = i; UI.printDetailed(UI.Module.ACCEL, "Creating tree ..."); int initialSize = 3 * (2 * 6 * n + 1); List<int> tempTree = new List<int>((initialSize + 3) / 4); BuildStats stats = new BuildStats(); Timer t = new Timer(); t.start(); buildHierarchy(tempTree, objects, stats); t.end(); UI.printDetailed(UI.Module.ACCEL, "Trimming tree ..."); tree = tempTree.ToArray(); // display stats stats.printStats(); UI.printDetailed(UI.Module.ACCEL, " * Creation time: %s", t); UI.printDetailed(UI.Module.ACCEL, " * Usage of init: %3d%%", 100 * tree.Length / initialSize); UI.printDetailed(UI.Module.ACCEL, " * Tree memory: %s", Memory.SizeOf(tree)); UI.printDetailed(UI.Module.ACCEL, " * Indices memory: %s", Memory.SizeOf(objects)); }
/** * Create a geometry from the specified primitive aggregate. The * acceleration structure for this object will be built on demand. * * @param primitives primitive list object */ public Geometry(PrimitiveList primitives) { tesselatable = null; this.primitives = primitives; accel = null; builtAccel = 0; builtTess = 1; // already tesselated }
/** * Create a geometry from the specified primitive aggregate. The * acceleration structure for this object will be built on demand. * * @param primitives primitive list object */ public Geometry(PrimitiveList primitives) { tesselatable = null; this.primitives = primitives; accel = null; builtAccel = 0; builtTess = 1; // already tesselated }
/// <summary> /// Converts a PrimitiveList into an array of elements of elementType /// </summary> private static object FillArrayFromPrimitiveList <T>(PrimitiveList primitiveList, Type elementType) { return(primitiveList .AsListOfPrimitive() .Select(pr => pr.ToObject(elementType)) .Cast <T>() .ToArray()); }
/// <summary> /// Fills an IList with contents of PrimitiveList. /// </summary> private static object FillListFromPrimitiveList(IList list, PrimitiveList primitiveList, Type elementType) { foreach (var primitive in primitiveList.Entries) { list.Add(primitive.ToObject(elementType)); } return(list); }
/** * Create a geometry from the specified tesselatable object. The actual * renderable primitives will be generated on demand. * * @param tesselatable tesselation object */ public Geometry(ITesselatable tesselatable) { this.tesselatable = tesselatable; primitives = null; accel = null; builtAccel = 0; builtTess = 0; acceltype = null; }
private static bool TryToPrimitiveList(Type type, object value, bool canReturnPrimitive, out DynamoDBEntry output) { var typeWrapper = TypeFactory.GetTypeInfo(type); Type elementType; if (!Utils.ImplementsInterface(type, typeof(ICollection <>)) || !Utils.IsPrimitive(elementType = typeWrapper.GetGenericArguments()[0])) { output = null; return(false); } IEnumerable enumerable = value as IEnumerable; Primitive primitive; // Strings are collections of chars, don't treat them as collections if (enumerable == null || value is string) { if (canReturnPrimitive && TypeFactory.GetTypeInfo(value.GetType()).IsAssignableFrom(TypeFactory.GetTypeInfo(elementType)) && TryToPrimitive(elementType, value, out primitive)) { output = primitive; return(true); } output = null; return(false); } PrimitiveList primitiveList = new PrimitiveList(); DynamoDBEntryType?listType = null; foreach (var item in enumerable) { if (TryToPrimitive(elementType, item, out primitive)) { if (listType.HasValue && listType.Value != primitive.Type) { throw new InvalidOperationException("List cannot contain a mix of different types"); } listType = primitive.Type; primitiveList.Entries.Add(primitive); } else { output = null; return(false); } } primitiveList.Type = listType.GetValueOrDefault(DynamoDBEntryType.String); output = primitiveList; return(true); }
internal PrimitiveList ItemsToPrimitiveList(IEnumerable items) { var inputType = items.GetType(); var elementType = Utils.GetPrimitiveElementType(inputType); var primitives = ToPrimitives(items, elementType); var pl = new PrimitiveList(primitives); return(pl); }
/** * Create a geometry from the specified tesselatable object. The actual * renderable primitives will be generated on demand. * * @param tesselatable tesselation object */ public Geometry(ITesselatable tesselatable) { this.tesselatable = tesselatable; primitives = null; accel = null; builtAccel = 0; builtTess = 0; acceltype = null; }
/// <summary> /// Converts an ICollection to a PrimitiveList /// </summary> private static PrimitiveList ToPrimitiveList(object coll, Type elementType) { var primitiveList = new PrimitiveList(); foreach (var item in (ICollection)coll) { primitiveList.Entries.Add(item.ToPrimitive(elementType)); } return(primitiveList); }
private static bool TryToPrimitiveList(Type type, object value, bool canReturnPrimitive, out DynamoDBEntry output) { Type elementType; if (!EntityUtils.ImplementsInterface(type, typeof(ICollection <>)) || !EntityUtils.IsPrimitive(elementType = type.GetGenericArguments()[0])) { output = null; return(false); } PrimitiveList primitiveList = new PrimitiveList(); ICollection collection = value as ICollection; Primitive primitive; if (collection == null) { if (canReturnPrimitive && value.GetType().IsAssignableFrom(elementType) && TryToPrimitive(elementType, value, out primitive)) { output = primitive; return(true); } output = null; return(false); } bool?isNumeric = null; foreach (var item in collection) { if (TryToPrimitive(elementType, item, out primitive)) { if (isNumeric.HasValue && isNumeric.Value != primitive.SaveAsNumeric) { throw new InvalidOperationException("List cannot contain a mix of numerics and non-numerics"); } isNumeric = primitive.SaveAsNumeric; primitiveList.Entries.Add(primitive); } else { output = null; return(false); } } primitiveList.SaveAsNumeric = isNumeric.HasValue ? isNumeric.Value : false; output = primitiveList; return(true); }
private static bool TryToPrimitiveList(Type type, object value, bool canReturnPrimitive, out DynamoDBEntry output) { Type elementType; if (!EntityUtils.ImplementsInterface(type, typeof(ICollection <>)) || !EntityUtils.IsPrimitive(elementType = type.GetGenericArguments()[0])) { output = null; return(false); } ICollection collection = value as ICollection; Primitive primitive; if (collection == null) { if (canReturnPrimitive && value.GetType().IsAssignableFrom(elementType) && TryToPrimitive(elementType, value, out primitive)) { output = primitive; return(true); } output = null; return(false); } PrimitiveList primitiveList = new PrimitiveList(); DynamoDBEntryType?listType = null; foreach (var item in collection) { if (TryToPrimitive(elementType, item, out primitive)) { if (listType.HasValue && listType.Value != primitive.Type) { throw new InvalidOperationException("List cannot contain a mix of different types"); } listType = primitive.Type; primitiveList.Entries.Add(primitive); } else { output = null; return(false); } } primitiveList.Type = listType.GetValueOrDefault(DynamoDBEntryType.String); output = primitiveList; return(true); }
public void CanSerializePrimitiveListStream() { var list = new PrimitiveList(); for (var n = 0; n < 10; n++) { list.List.Add(Primitives.Create(n)); } Assert.IsTrue(this.Serializer.CanSerializeStream <PrimitiveList>(list)); }
public DynamoDBEntry ToEntry (object value) { Coordinate cord = value as Coordinate; var pList = new PrimitiveList (DynamoDBEntryType.Numeric); if (cord != null) { pList.Add (cord.Latitude); pList.Add (cord.Longitude); pList.Add (cord.AccuracyInMeters); } return pList; }
public DynamoDBEntry ToEntry(object value) { Coordinate cord = value as Coordinate; var pList = new PrimitiveList(DynamoDBEntryType.Numeric); if (cord != null) { pList.Add(cord.Latitude); pList.Add(cord.Longitude); pList.Add(cord.AccuracyInMeters); } return(pList); }
public override bool TryTo(object value, out PrimitiveList pl) { var items = value as IEnumerable; if (items != null) { pl = Conversion.ItemsToPrimitiveList(items); return(true); } pl = null; return(false); }
public static Instance createTemporary(PrimitiveList primitives, Matrix4 transform, IShader shader) { Instance i = new Instance(); i.o2w = new MovingMatrix4(transform); i.w2o = i.o2w.inverse(); if (i.w2o == null) { UI.printError(UI.Module.GEOM, "Unable to compute transform inverse"); return null; } i.geometry = new Geometry(primitives); i.shaders = new IShader[] { shader }; i.updateBounds(); return i; }
/** * Get the three triangle corners in object space if the hit object is a * mesh, returns false otherwise. * * @param p array of 3 points * @return <code>true</code> if the points were read succesfully, * <code>false</code>otherwise */ public bool getTrianglePoints(Point3[] p) { PrimitiveList prims = instance.getGeometry().getPrimitiveList(); if (prims is TriangleMesh) { TriangleMesh m = (TriangleMesh)prims; m.getPoint(primitiveID, 0, p[0] = new Point3()); m.getPoint(primitiveID, 1, p[1] = new Point3()); m.getPoint(primitiveID, 2, p[2] = new Point3()); return(true); } return(false); }
// PrimitiveList <--> List private static bool TryFromPrimitiveList(Type targetType, PrimitiveList value, out object output) { var targetTypeWrapper = TypeFactory.GetTypeInfo(targetType); Type elementType; if ((!Utils.ImplementsInterface(targetType, typeof(ICollection <>)) && !Utils.ImplementsInterface(targetType, typeof(IList))) || !Utils.CanInstantiate(targetType) || !Utils.IsPrimitive(elementType = targetTypeWrapper.GetGenericArguments()[0])) { output = null; return(false); } var collection = Utils.Instantiate(targetType); IList ilist = collection as IList; bool useIListInterface = ilist != null; MethodInfo collectionAdd = null; if (!useIListInterface) { collectionAdd = targetTypeWrapper.GetMethod("Add"); } foreach (Primitive primitive in value.Entries) { object primitiveValue; if (TryFromPrimitive(elementType, primitive, out primitiveValue)) { if (useIListInterface) { ilist.Add(primitiveValue); } else { collectionAdd.Invoke(collection, new object[] { primitiveValue }); } } else { output = null; return(false); } } output = collection; return(true); }
public override int GetHashCode() { unchecked { var hashCode = DateValue.GetHashCode(); hashCode = (hashCode * 397) ^ (IgnoredProperty != null ? IgnoredProperty.GetHashCode() : 0); hashCode = (hashCode * 397) ^ IntegralValue; hashCode = (hashCode * 397) ^ (StringValue != null ? StringValue.GetHashCode() : 0); hashCode = (hashCode * 397) ^ NullableProperty.GetHashCode(); hashCode = (hashCode * 397) ^ (Component != null ? Component.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (PrimitiveList != null ? PrimitiveList.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (ComplexCollection != null ? ComplexCollection.GetHashCode() : 0); return(hashCode); } }
private void RenderList() { var searchString = new Regex(".*" + SearchBox.Text.ToLowerInvariant() + ".*"); PrimitiveList.ClearSelected(); PrimitiveList.Items.Clear(); foreach (var prim in CurrentFullList) { if (searchString.IsMatch(prim.ToString().ToLowerInvariant())) { PrimitiveList.Items.Add(prim); } } }
private void UpdatePrimitiveList() { var searchString = new Regex(".*" + SearchBox.Text.ToLower() + ".*"); PrimitiveList.ClearSelected(); lock (EditorLock) Editor.ClearPlacement(); PrimitiveList.Items.Clear(); foreach (var prim in CurrentFullList) { if (searchString.IsMatch(prim.ToString().ToLower())) { PrimitiveList.Items.Add(prim); } } }
public static Instance createTemporary(PrimitiveList primitives, Matrix4 transform, IShader shader) { Instance i = new Instance(); i.o2w = new MovingMatrix4(transform); i.w2o = i.o2w.inverse(); if (i.w2o == null) { UI.printError(UI.Module.GEOM, "Unable to compute transform inverse"); return(null); } i.geometry = new Geometry(primitives); i.shaders = new IShader[] { shader }; i.updateBounds(); return(i); }
public DynamoDBEntry ToEntry(object value) { if (value == null) { return(null); } var dictionary = (IDictionary <string, TimeSpan>)value; var primitiveList = new PrimitiveList(DynamoDBEntryType.String); foreach (var keyValuePair in dictionary) { primitiveList.Add(new Primitive(string.Format("{0}@{1}", keyValuePair.Key, keyValuePair.Value))); } return(primitiveList); }
public bool Equals(ComplexTypeClass other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(DateValue.Equals(other.DateValue) && IntegralValue == other.IntegralValue && string.Equals(StringValue, other.StringValue) && NullableProperty == other.NullableProperty && Equals(Component, other.Component) && (PrimitiveList != null && PrimitiveList.SequenceEqual(other.PrimitiveList) || PrimitiveList == null && other.PrimitiveList == null) && (ComplexCollection != null && ComplexCollection.SequenceEqual(other.ComplexCollection) || ComplexCollection == null && other.ComplexCollection == null)); }
public object FromEntry(DynamoDBEntry entry) { PrimitiveList pList = entry as PrimitiveList; if (pList == null) { throw new ArgumentOutOfRangeException(); } var sList = pList.AsListOfString(); var hashSet = new HashSet <string> (); foreach (var item in sList) { hashSet.Add(item); } return(hashSet); }
/// <summary> /// If value is HashSet{T}, converts the items to PrimitiveList /// </summary> /// <param name="value"></param> /// <param name="pl"></param> /// <returns></returns> public override bool TryTo(object value, out PrimitiveList pl) { var inputType = value.GetType(); var inputTypeInfo = TypeFactory.GetTypeInfo(inputType); if (inputTypeInfo.IsGenericType) { var genericTypeInfo = TypeFactory.GetTypeInfo(inputTypeInfo.GetGenericTypeDefinition()); if (setTypeInfo.IsAssignableFrom(genericTypeInfo)) { pl = Conversion.ItemsToPrimitiveList(value as IEnumerable); return(true); } } pl = null; return(false); }
public bool Update(ParameterList pl, SunflowAPI api) { acceltype = pl.getstring("accel", acceltype); // clear up old tesselation if it exists if (tesselatable != null) { primitives = null; builtTess = 0; } // clear acceleration structure so it will be rebuilt accel = null; builtAccel = 0; if (tesselatable != null) { return(tesselatable.Update(pl, api)); } // update primitives return(primitives.Update(pl, api)); }
/** * Creates an empty scene. */ public Scene() { lightServer = new LightServer(this); instanceList = new InstanceList(); infiniteInstanceList = new InstanceList(); acceltype = "auto"; bakingViewDependent = false; bakingInstance = null; bakingPrimitives = null; bakingAccel = null; camera = null; imageWidth = 640; imageHeight = 480; threads = 0; lowPriority = true; rebuildAccel = true; }
private void init() { compiled = false; root = new OctreeNode(); bigObjects = new PrimitiveList(); }
public DynamoDBEntry ToEntry(object value) { if (value == null) { return null; } var dictionary = (IDictionary<string, TimeSpan>)value; var primitiveList = new PrimitiveList(DynamoDBEntryType.String); foreach (var keyValuePair in dictionary) { primitiveList.Add(new Primitive(string.Format("{0}@{1}", keyValuePair.Key, keyValuePair.Value))); } return primitiveList; }
private BoundingBox surroundingBox(PrimitiveList primitives) { List<BoundingBox> boxes = new List<BoundingBox>(primitives.Count); foreach (Primitive primitive in root.primitives) { boxes.Add(primitive.BoundingBox); } return BoundingBox.Surrounding(boxes); }
public bool update(ParameterList pl, SunflowAPI api) { acceltype = pl.getstring("accel", acceltype); // clear up old tesselation if it exists if (tesselatable != null) { primitives = null; builtTess = 0; } // clear acceleration structure so it will be rebuilt accel = null; builtAccel = 0; if (tesselatable != null) return tesselatable.update(pl, api); // update primitives return primitives.update(pl, api); }
/// <summary> /// If value is HashSet{T}, converts the items to PrimitiveList /// </summary> /// <param name="value"></param> /// <param name="pl"></param> /// <returns></returns> public override bool TryTo(object value, out PrimitiveList pl) { var inputType = value.GetType(); var inputTypeInfo = TypeFactory.GetTypeInfo(inputType); if (inputTypeInfo.IsGenericType) { var genericTypeInfo = TypeFactory.GetTypeInfo(inputTypeInfo.GetGenericTypeDefinition()); if (setTypeInfo.IsAssignableFrom(genericTypeInfo)) { pl = Conversion.ItemsToPrimitiveList(value as IEnumerable); return true; } } pl = null; return false; }
public void build(PrimitiveList primitives) { this.primitives = primitives; n = primitives.getNumPrimitives(); }
// Attempts to decode a particular DynamoDBEntry. // May throw exceptions, in particular if the data is not base64 encoded private static bool TryDecodeBase64(DynamoDBEntry entry, out DynamoDBEntry decodedEntry) { decodedEntry = null; // Convert string primitive (S) to binary primitive (B) var primitive = entry as Primitive; if (primitive != null && primitive.Type == DynamoDBEntryType.String) { // Decode the contents var base64 = primitive.Value as string; byte[] bytes; if (!TryDecodeBase64(base64, out bytes)) return false; // Store as binary primitive (B) decodedEntry = new Primitive(bytes); return true; } // Convert string set (SS) to binary set (BS) var primitiveList = entry as PrimitiveList; if (primitiveList != null && primitiveList.Type == DynamoDBEntryType.String) { var decodedList = new PrimitiveList(DynamoDBEntryType.Binary); foreach(var item in primitiveList.Entries) { // Attempt to decode DynamoDBEntry decodedItem; if (!TryDecodeBase64(item, out decodedItem)) return false; // The decoded item must be a Primitive Primitive decodedPrimitive = decodedItem as Primitive; if (decodedPrimitive == null) return false; decodedList.Add(decodedPrimitive); } decodedEntry = decodedList; return true; } // In a given list (L), convert every string primitive (S) to binary primitive (B) // Non-strings and strings that cannot be converted will be left as-is var dynamoDBList = entry as DynamoDBList; if (dynamoDBList != null) { var decodedList = new DynamoDBList(); foreach(var item in dynamoDBList.Entries) { DynamoDBEntry decodedItem; if (!TryDecodeBase64(item, out decodedItem)) { // if decoding could not succeed, store same item decodedItem = item; } decodedList.Add(decodedItem); } decodedEntry = decodedList; return true; } return false; }
public void build(PrimitiveList primitives) { UI.printDetailed(UI.Module.ACCEL, "KDTree settings"); UI.printDetailed(UI.Module.ACCEL, " * Max Leaf Size: {0}", maxPrims); UI.printDetailed(UI.Module.ACCEL, " * Max Depth: {0}", MAX_DEPTH); UI.printDetailed(UI.Module.ACCEL, " * Traversal cost: {0}", TRAVERSAL_COST); UI.printDetailed(UI.Module.ACCEL, " * Intersect cost: {0}", INTERSECT_COST); UI.printDetailed(UI.Module.ACCEL, " * Empty bonus: {0}", EMPTY_BONUS); UI.printDetailed(UI.Module.ACCEL, " * Dump leaves: {0}", dump ? "enabled" : "disabled"); Timer total = new Timer(); total.start(); primitiveList = primitives; // get the object space bounds bounds = primitives.getWorldBounds(null); int nPrim = primitiveList.getNumPrimitives(), nSplits = 0; BuildTask task = new BuildTask(nPrim); Timer prepare = new Timer(); prepare.start(); for (int i = 0; i < nPrim; i++) { for (int axis = 0; axis < 3; axis++) { float ls = primitiveList.getPrimitiveBound(i, 2 * axis + 0); float rs = primitiveList.getPrimitiveBound(i, 2 * axis + 1); if (ls == rs) { // flat in this dimension task.splits[nSplits] = pack(ls, PLANAR, axis, i); nSplits++; } else { task.splits[nSplits + 0] = pack(ls, OPENED, axis, i); task.splits[nSplits + 1] = pack(rs, CLOSED, axis, i); nSplits += 2; } } } task.n = nSplits; prepare.end(); Timer t = new Timer(); List<int> tempTree = new List<int>(); List<int> tempList = new List<int>(); tempTree.Add(0); tempTree.Add(1); t.start(); // sort it Timer sorting = new Timer(); sorting.start(); radix12(task.splits, task.n); sorting.end(); // build the actual tree BuildStats stats = new BuildStats(); buildTree(bounds.getMinimum().x, bounds.getMaximum().x, bounds.getMinimum().y, bounds.getMaximum().y, bounds.getMinimum().z, bounds.getMaximum().z, task, 1, tempTree, 0, tempList, stats); t.end(); // write out arrays // free some memory task = null; tree = tempTree.ToArray(); tempTree = null; this.primitives = tempList.ToArray(); tempList = null; total.end(); // display some extra info stats.printStats(); UI.printDetailed(UI.Module.ACCEL, " * Node memory: {0}", Memory.SizeOf(tree)); UI.printDetailed(UI.Module.ACCEL, " * Object memory: {0}", Memory.SizeOf(this.primitives)); UI.printDetailed(UI.Module.ACCEL, " * Prepare time: {0}", prepare); UI.printDetailed(UI.Module.ACCEL, " * Sorting time: {0}", sorting); UI.printDetailed(UI.Module.ACCEL, " * Tree creation: {0}", t); UI.printDetailed(UI.Module.ACCEL, " * Build time: {0}", total); if (dump) { try { UI.printInfo(UI.Module.ACCEL, "Dumping mtls to {0}.mtl ...", dumpPrefix); StreamWriter mtlFile = new StreamWriter(dumpPrefix + ".mtl"); int maxN = stats.maxObjects; for (int n = 0; n <= maxN; n++) { float blend = (float)n / (float)maxN; Color nc; if (blend < 0.25) nc = Color.blend(Color.BLUE, Color.GREEN, blend / 0.25f); else if (blend < 0.5) nc = Color.blend(Color.GREEN, Color.YELLOW, (blend - 0.25f) / 0.25f); else if (blend < 0.75) nc = Color.blend(Color.YELLOW, Color.RED, (blend - 0.50f) / 0.25f); else nc = Color.MAGENTA; mtlFile.WriteLine(string.Format("newmtl mtl{0}", n)); float[] rgb = nc.getRGB(); mtlFile.WriteLine("Ka 0.1 0.1 0.1"); mtlFile.WriteLine(string.Format("Kd {0}g {1}g {2}g", rgb[0], rgb[1], rgb[2])); mtlFile.WriteLine("illum 1\n"); } StreamWriter objFile = new StreamWriter(dumpPrefix + ".obj"); UI.printInfo(UI.Module.ACCEL, "Dumping tree to {0}.obj ...", dumpPrefix); dumpObj(0, 0, maxN, new BoundingBox(bounds), objFile, mtlFile); objFile.Close(); mtlFile.Close(); } catch (Exception e) { Console.WriteLine(e); } } }
public RenderObjectHandle(PrimitiveList prims) { obj = new Geometry(prims); type = RenderObjectType.GEOMETRY; }
public void put(string name, PrimitiveList primitives) { renderObjects[name] = new RenderObjectHandle(primitives); }
/** * Render the scene using the specified options, image sampler and display. * * @param options rendering options object * @param sampler image sampler * @param display display to send the image to, a default display will * be created if <code>null</code> */ public void render(Options options, ImageSampler sampler, IDisplay display) { if (display == null) display = null;// new FrameDisplay(); if (bakingInstance != null) { UI.printDetailed(UI.Module.SCENE, "Creating primitives for lightmapping ..."); bakingPrimitives = bakingInstance.getBakingPrimitives(); if (bakingPrimitives == null) { UI.printError(UI.Module.SCENE, "Lightmap baking is not supported for the given instance."); return; } int n = bakingPrimitives.getNumPrimitives(); UI.printInfo(UI.Module.SCENE, "Building acceleration structure for lightmapping ({0} num primitives) ...", n); bakingAccel = AccelerationStructureFactory.create("auto", n, true); bakingAccel.build(bakingPrimitives); } else { bakingPrimitives = null; bakingAccel = null; } bakingViewDependent = options.getbool("baking.viewdep", bakingViewDependent); if ((bakingInstance != null && bakingViewDependent && camera == null) || (bakingInstance == null && camera == null)) { UI.printError(UI.Module.SCENE, "No camera found"); return; } // read from options threads = options.getInt("threads", 0); lowPriority = options.getbool("threads.lowPriority", true); imageWidth = options.getInt("resolutionX", 640); imageHeight = options.getInt("resolutionY", 480); // limit resolution to 16k imageWidth = MathUtils.clamp(imageWidth, 1, 1 << 14); imageHeight = MathUtils.clamp(imageHeight, 1, 1 << 14); // get acceleration structure info // count scene primitives long numPrimitives = 0; for (int i = 0; i < instanceList.getNumPrimitives(); i++) numPrimitives += instanceList.getNumPrimitives(i); UI.printInfo(UI.Module.SCENE, "Scene stats:"); UI.printInfo(UI.Module.SCENE, " * Infinite instances: {0}", infiniteInstanceList.getNumPrimitives()); UI.printInfo(UI.Module.SCENE, " * Instances: {0}", instanceList.getNumPrimitives()); UI.printInfo(UI.Module.SCENE, " * Primitives: {0}", numPrimitives); string accelName = options.getstring("accel", null); if (accelName != null) { rebuildAccel = rebuildAccel || acceltype != accelName; acceltype = accelName; } UI.printInfo(UI.Module.SCENE, " * Instance accel: {0}", acceltype); if (rebuildAccel) { intAccel = AccelerationStructureFactory.create(acceltype, instanceList.getNumPrimitives(), false); intAccel.build(instanceList); rebuildAccel = false; } UI.printInfo(UI.Module.SCENE, " * Scene bounds: {0}", getBounds()); UI.printInfo(UI.Module.SCENE, " * Scene center: {0}", getBounds().getCenter()); UI.printInfo(UI.Module.SCENE, " * Scene diameter: {0}", getBounds().getExtents().Length()); UI.printInfo(UI.Module.SCENE, " * Lightmap bake: {0}", bakingInstance != null ? (bakingViewDependent ? "view" : "ortho") : "off"); if (sampler == null) return; if (!lightServer.build(options)) return; // render UI.printInfo(UI.Module.SCENE, "Rendering ..."); sampler.prepare(options, this, imageWidth, imageHeight); sampler.render(display); lightServer.showStats(); // discard baking tesselation/accel structure bakingPrimitives = null; bakingAccel = null; UI.printInfo(UI.Module.SCENE, "Done."); }
/// <summary> /// Splits node's primitives into 8 new children nodes. /// </summary> private void split() { if (boundingBox == null) throw new Exception("Cannot split null bounding box"); try { this.childs = new OctreeNode[8]; for (int i = 0; i < 8; i++) { childs[i] = new OctreeNode(); childs[i].boundingBox = new BoundingBox(new Vector(), new Vector()); } double dx2 = (boundingBox.RightBottomBack.X - boundingBox.LeftTopFront.X) / 2; double dy2 = (boundingBox.RightBottomBack.Y - boundingBox.LeftTopFront.Y) / 2; double dz2 = (boundingBox.RightBottomBack.Z - boundingBox.LeftTopFront.Z) / 2; childs[0].boundingBox.LeftTopFront = boundingBox.LeftTopFront; childs[1].boundingBox.LeftTopFront = boundingBox.LeftTopFront + new Vector(dx2, 0, 0); childs[2].boundingBox.LeftTopFront = boundingBox.LeftTopFront + new Vector(0, dy2, 0); childs[3].boundingBox.LeftTopFront = boundingBox.LeftTopFront + new Vector(dx2, dy2, 0); childs[4].boundingBox.LeftTopFront = boundingBox.LeftTopFront + new Vector(0, 0, dz2); childs[5].boundingBox.LeftTopFront = boundingBox.LeftTopFront + new Vector(dx2, 0, dz2); childs[6].boundingBox.LeftTopFront = boundingBox.LeftTopFront + new Vector(0, dy2, dz2); childs[7].boundingBox.LeftTopFront = boundingBox.LeftTopFront + new Vector(dx2, dy2, dz2); Vector sizeVector = new Vector(dx2, dy2, dz2); // all childs same size for (int i = 0; i < 8; i++) { childs[i].boundingBox.RightBottomBack = childs[i].boundingBox.LeftTopFront + sizeVector; } // distribute primitives into children foreach (Primitive primitive in primitives) { // primitive may fall into multiple children at the same time // ideally it will fall in only 1 child for (int i = 0; i < 8; i++) { if (primitive.BoundingBox.Intersects(childs[i].boundingBox)) { childs[i].Add(primitive); } } } primitives = null; } catch { // in case of exception clean up any inconsistencies this.childs = null; this.boundingBox = BoundingBox.Zero; throw; } }
private List<J3DRenderer.VertexFormatLayout> BuildVertexArraysFromFile() { List<J3DRenderer.VertexFormatLayout> finalData = new List<J3DRenderer.VertexFormatLayout>(); //Now, let's try to get our data. for (uint i = 0; i < _file.Shapes.GetBatchCount(); i++) { J3DFormat.Batch batch = _file.Shapes.GetBatch(i); RenderBatch renderBatch = new RenderBatch(); _renderList.Add(renderBatch); //Console.WriteLine("[{0}] Unk0: {5}, Attb: {6} Mtx Type: {1} #Packets {2}[{3}] Matrix Index: {4}", i, batch.MatrixType, batch.PacketCount, batch.PacketIndex, batch.FirstMatrixIndex, batch.Unknown0, batch.AttribOffset); uint attributeCount = 0; for (uint attribIndex = 0; attribIndex < 13; attribIndex++) { J3DFormat.BatchAttribute attrib = _file.Shapes.GetAttribute(attribIndex, batch.AttribOffset); if (attrib.AttribType == J3DFormat.ArrayTypes.NullAttr) break; attributeCount++; } for (ushort p = 0; p < batch.PacketCount; p++) { RenderPacket renderPacket = new RenderPacket(); renderBatch.Packets.Add(renderPacket); //Matrix Data J3DFormat.PacketMatrixData pmd = _file.Shapes.GetPacketMatrixData((ushort)(batch.FirstMatrixIndex + p)); renderPacket.DrawIndexes = new ushort[pmd.Count]; for (ushort mtx = 0; mtx < pmd.Count; mtx++) { //Console.WriteLine("{4} {0} Packet: {1} Index: {2} PMD Unknown: {3}", i, p, _file.Shapes.GetMatrixTableIndex((ushort) (pmd.FirstIndex + mtx)), pmd.Unknown, mtx); renderPacket.DrawIndexes[mtx] = _file.Shapes.GetMatrixTableIndex((ushort)(pmd.FirstIndex + mtx)); } J3DFormat.BatchPacketLocation packetLoc = _file.Shapes.GetBatchPacketLocation((ushort)(batch.PacketIndex + p)); uint numPrimitiveBytesRead = packetLoc.Offset; while (numPrimitiveBytesRead < packetLoc.Offset + packetLoc.PacketSize) { J3DFormat.BatchPrimitive primitive = _file.Shapes.GetPrimitive(numPrimitiveBytesRead); numPrimitiveBytesRead += J3DFormat.BatchPrimitive.Size; //Game pads the chunks out with zeros, so this is signal for early break. if (primitive.Type == 0) { break; } var primList = new PrimitiveList(); primList.VertexCount = primitive.VertexCount; primList.VertexStart = finalData.Count; primList.DrawType = primitive.Type == J3DFormat.PrimitiveTypes.TriangleStrip ? PrimitiveType.TriangleStrip : PrimitiveType.TriangleFan; //Todo: More support renderPacket.PrimList.Add(primList); for (int vert = 0; vert < primitive.VertexCount; vert++) { J3DRenderer.VertexFormatLayout newVertex = new J3DRenderer.VertexFormatLayout(); for (uint vertIndex = 0; vertIndex < attributeCount; vertIndex++) { var batchAttrib = _file.Shapes.GetAttribute(vertIndex, batch.AttribOffset); ushort curIndex = _file.Shapes.GetPrimitiveIndex(numPrimitiveBytesRead, batchAttrib); switch (batchAttrib.AttribType) { case J3DFormat.ArrayTypes.Position: newVertex.Position = _file.Vertexes.GetPosition(curIndex); break; case J3DFormat.ArrayTypes.Normal: newVertex.Color = new Vector4(_file.Vertexes.GetNormal(curIndex, 14), 1); //temp break; case J3DFormat.ArrayTypes.Color0: newVertex.Color = _file.Vertexes.GetColor0(curIndex); break; case J3DFormat.ArrayTypes.Tex0: newVertex.TexCoord = _file.Vertexes.GetTex0(curIndex, 8); break; case J3DFormat.ArrayTypes.PositionMatrixIndex: //Console.WriteLine("B: {0} P: {1} Prim: {2} Vert{3} Index: {4}", i, p, renderPacket.PrimList.Count, vert, curIndex); primList.PosMatrixIndex.Add(curIndex); break; default: Console.WriteLine("Unknown AttribType {0}, Index: {1}", batchAttrib.AttribType, curIndex); break; } numPrimitiveBytesRead += GetAttribElementSize(batchAttrib.DataType); } //Add our vertex to our list of Vertexes finalData.Add(newVertex); } //Console.WriteLine("Batch {0} Prim {1} #Vertices with PosMtxIndex: {2}", i, p, primList.PosMatrixIndex.Count); } } //Console.WriteLine("Finished batch {0}, triangleStrip count: {1}", i, _renderList.Count); } return finalData; }
public NullAccelerator() { primitives = null; n = 0; }
private void tesselate() { lock (lockObj) { // double check flag if (builtTess != 0) return; if (tesselatable != null && primitives == null) { UI.printInfo(UI.Module.GEOM, "Tesselating geometry ..."); primitives = tesselatable.tesselate(); if (primitives == null) UI.printError(UI.Module.GEOM, "Tesselation failed - geometry will be discarded"); else UI.printDetailed(UI.Module.GEOM, "Tesselation produced {0} primitives", primitives.getNumPrimitives()); } builtTess = 1; } }
public void build(PrimitiveList primitives) { Timer t = new Timer(); t.start(); this.primitives = primitives; int n = primitives.getNumPrimitives(); // compute bounds bounds = primitives.getWorldBounds(null); // create grid from number of objects bounds.enlargeUlps(); Vector3 w = bounds.getExtents(); double s = Math.Pow((w.x * w.y * w.z) / n, 1 / 3.0); nx = MathUtils.clamp((int)((w.x / s) + 0.5), 1, 128); ny = MathUtils.clamp((int)((w.y / s) + 0.5), 1, 128); nz = MathUtils.clamp((int)((w.z / s) + 0.5), 1, 128); voxelwx = w.x / nx; voxelwy = w.y / ny; voxelwz = w.z / nz; invVoxelwx = 1 / voxelwx; invVoxelwy = 1 / voxelwy; invVoxelwz = 1 / voxelwz; UI.printDetailed(UI.Module.ACCEL, "Creating grid: %dx%dx%d ...", nx, ny, nz); List<int>[] buildCells = new List<int>[nx * ny * nz]; // add all objects into the grid cells they overlap int[] imin = new int[3]; int[] imax = new int[3]; int numCellsPerObject = 0; for (int i = 0; i < n; i++) { getGridIndex(primitives.getPrimitiveBound(i, 0), primitives.getPrimitiveBound(i, 2), primitives.getPrimitiveBound(i, 4), imin); getGridIndex(primitives.getPrimitiveBound(i, 1), primitives.getPrimitiveBound(i, 3), primitives.getPrimitiveBound(i, 5), imax); for (int ix = imin[0]; ix <= imax[0]; ix++) { for (int iy = imin[1]; iy <= imax[1]; iy++) { for (int iz = imin[2]; iz <= imax[2]; iz++) { int idx = ix + (nx * iy) + (nx * ny * iz); if (buildCells[idx] == null) buildCells[idx] = new List<int>(); buildCells[idx].Add(i); numCellsPerObject++; } } } } UI.printDetailed(UI.Module.ACCEL, "Building cells ..."); int numEmpty = 0; int numInFull = 0; cells = new int[nx * ny * nz][]; //int i = 0; //foreach (List<int> cell in buildCells) for (int i = 0; i < buildCells.Length; i++) { if (buildCells[i] != null) { if (buildCells[i].Count == 0) { numEmpty++; buildCells[i] = null; } else { cells[i] = buildCells[i].ToArray(); numInFull += buildCells[i].Count; } } else numEmpty++; //i++; } t.end(); UI.printDetailed(UI.Module.ACCEL, "Uniform grid statistics:"); UI.printDetailed(UI.Module.ACCEL, " * Grid cells: {0}", cells.Length); UI.printDetailed(UI.Module.ACCEL, " * Used cells: {0}", cells.Length - numEmpty); UI.printDetailed(UI.Module.ACCEL, " * Empty cells: {0}", numEmpty); UI.printDetailed(UI.Module.ACCEL, " * Occupancy: {0}", 100.0 * (cells.Length - numEmpty) / cells.Length); UI.printDetailed(UI.Module.ACCEL, " * Objects/Cell: {0}", (double)numInFull / (double)cells.Length); UI.printDetailed(UI.Module.ACCEL, " * Objects/Used Cell: {0}", (double)numInFull / (double)(cells.Length - numEmpty)); UI.printDetailed(UI.Module.ACCEL, " * Cells/Object: {0}", (double)numCellsPerObject / (double)n); UI.printDetailed(UI.Module.ACCEL, " * Build time: {0}", t.ToString()); }